2012-09-17 28 views
3

我有3个表(products,custom_attribute,attribute_value)需要链接在一起。我有attribute_value_maps表,它有product_id,custom_attribute_idattribute_value_idRails的三种方式nested_attributes has_many

我的产品型号为accepts_nested_attributes_for :attribute_value_mapsaccepts_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]"> 

控制器是基本@product.update_attributes(paras[:product])

这将正确创建attribute_value记录,但attribute_value_map记录保存为零custom_attribute_id

问题1:有没有一种简单的方法让attribute_value_map记录以这种方式保存在正确的custom_attribute_id

问题2:说已经有了另外一个映射记录,如果我添加的输入与名称product[attribute_values_attributes][1][attribute_value_map_id],它只是骂我说,这不是一个有效的字段。如何在创建新的attribute_value时更新现有的地图记录?

编辑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 

custom_attribute模型

has_many :attribute_value_maps 

ATTRIBUTE_VALUE模型

belongs_to :custom_attribute 
has_many :attribute_value_maps 

attribute_value_map模型

belongs_to :product 
belongs_to :custom_attribute 
belongs_to :attribute_value 
+0

你可以发布这3个模型之间的关系代码吗?产品,custom_attribute,attribute_value –

回答

0

如果我明白你在这里做什么,我想你可能会在和自己的使用ActiveRecord了不少苦。

这种动态属性的就是创建NoSQL数据库。你可能要考虑像Mongoid/MongoDB的是否是一个更好的选择:

最起码,你可能要考虑寻找的ActiveRecord的序列化功能:

http://api.rubyonrails.org/classes/ActiveRecord/Base.html看到的序列化功能向底部。

如果你使用的是Postgres,你可能想看看成采用原生数据库格式允许属性字段建立索引的hstore扩展:

https://github.com/softa/activerecord-postgres-hstore

希望上面的东西,有助于你: )