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

时间:2015-01-12 11:56:08

标签: inheritance ruby-on-rails-4 mongoid nested-attributes strong-parameters

我有以下代码框架Column嵌入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

现在我想将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.

1 个答案:

答案 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)

这解决了我的问题。