我有 3 个表(products
、custom_attribute
、attribute_value
)需要链接在一起。我有一个 attribute_value_maps
表,其中包含 product_id
、custom_attribute_id
和 attribute_value_id
。
我的产品模型 accepts_nested_attributes_for :attribute_value_maps
和 accepts_nested_attributes_for :attribute_values
。
我的产品表单有一个新的 attribute_values 字段,如下所示:
<input id="product_attribute_values_attributes_1_custom_attribute_id" name="product[attribute_values_attributes][1][custom_attribute_id]" value="1" type="hidden">
<input id="product_attribute_values_attributes_1_attribute_value_name" name="product[attribute_values_attributes][1][name]">
Controller 是基本的@product.update_attributes(paras[:product])
。
这会正确创建 attribute_value
记录,但 attribute_value_map
记录保存为 nil custom_attribute_id
。
问题 1:是否有一种简单的方法可以让 attribute_value_map
记录以这种方式使用正确的 custom_attribute_id
进行保存?
问题 2:假设已经有一个 map 记录,如果我添加名称为 product[attribute_values_attributes][1][attribute_value_map_id]
的输入,它只会大喊我说那不是一个有效的领域。如何在创建新的 attribute_value 时更新现有的 map 记录?
编辑 1:要求提供更多详细信息
产品型号:
has_many :custom_attributes, :through => :attribute_value_maps
has_many :attribute_value_maps, :dependent => :destroy
has_man :attribute_values, :through => :attribute_value_maps
accepts_nested_attributes_for :attribute_value_maps
accepts_nested_attributes_for :attribute_values
自定义属性模型
has_many :attribute_value_maps
属性值模型
belongs_to :custom_attribute
has_many :attribute_value_maps
attribute_value_map 模型
belongs_to :product
belongs_to :custom_attribute
belongs_to :attribute_value
最佳答案
如果我理解您在这里尝试做什么,我认为您可能会为使用 ActiveRecord 设置很多痛苦。
这种动态属性是创建 NoSQL 数据库的原因。您可能需要考虑像 Mongoid/MongoDB 这样的东西是否是更好的选择:
至少,您可能需要考虑查看 ActiveRecord 的序列化功能:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html请参阅底部的序列化函数。
如果您使用的是 Postgres,您可能需要查看 hstore 扩展,它使用 native 数据库格式来允许对属性字段进行索引:
https://github.com/softa/activerecord-postgres-hstore
希望以上内容对您有所帮助:)
关于ruby-on-rails - 具有三种方式的 Rails 嵌套属性 has_many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12465195/