Rails 4 Mongoid 继承+强参数+嵌套属性

Rails4 Mongoid inheritance + Strong Paramters +Nested attributes

我有以下代码框架,其中 Column embeds_many Contents 类型 ImageMap:

class Column
  include Mongoid::Document

  embeds_many: contents
  accepts_nested_attributes_for :contents, allow_destroy: true
end

class content
  include Mongoid::Document

  field :description
end

class Image < Content
  field :src, type: String
end

class Map < Content      
  field :latitude, type: String
  field :longitude, type: String
end

现在我想将 JSON 从我的 Angular 视图传递到 columns_controller 以创建一个包含两个内容的列;图片和地图。

我试图传递以下哈希值:

{'column' => 'contents_attributes' => [{_type: 'Image', description: 'image description', src: 'path/to/image'}, {_type: 'Map', description: 'map description', latitude: '25.3321', longitude: '35.32423'}]}

column_params方法是:

def column_params
  params.require(:column).permit(:_id, contents_attributes: [:_id, _type, :description, :src, :latitude, :longitude]) 
end

以上引发了以下错误:

Attempted to set a value for '_type' which is not allowed on the model Content.

作为文件 lib/mongoid/relations/builders/nested_attributes/many.rb 中 mongoid gem(版本 4.0.0)的解决方法,我在第 [=14] 行的方法 process_attributes 中更改了对象的创建=]成为

klass = attrs[:_type].try(:constantize) || metadata.klass
existing.push(Factory.build(klass, attrs)) unless destroyable?(attrs)

而不是

existing.push(Factory.build(metadata.klass, attrs)) unless destroyable?(attrs)

这解决了我的问题。