【问题标题】:Rails4 Mongoid inheritance + Strong Paramters +Nested attributesRails 4 Mongoid继承+强参数+嵌套属性
【发布时间】:2015-01-12 11:56:07
【问题描述】:

我有以下代码框架,其中 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.

【问题讨论】:

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


    【解决方案1】:

    作为文件lib/mongoid/relations/builders/nested_attributes/many.rb 中的mongoid gem(4.0.0 版)的一种解决方法,我将109 行中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)
    

    这解决了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多