我有以下代码框架Column
嵌入Contents
类型Image
和Map
:
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
现在我想将Angular
视图中的JSON传递给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.
答案 0 :(得分:0)
作为文件lib/mongoid/relations/builders/nested_attributes/many.rb
中mongoid gem(版本4.0.0)的变通方法,我在第process_attributes
行的方法109
中更改了对象的创建
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)
这解决了我的问题。