【问题标题】:Rails nested_attributes with three way has_manyRails 嵌套属性与三种方式 has_many
【发布时间】:2012-09-17 18:34:25
【问题描述】:

我有 3 个表(productscustom_attributeattribute_value)需要链接在一起。我有attribute_value_maps 表,其中有product_idcustom_attribute_idattribute_value_id

我的产品型号accepts_nested_attributes_for :attribute_value_mapsaccepts_nested_attributes_for :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] 的输入,它只会对我大喊大叫,说这不是一个有效的字段。如何在创建新的属性值时更新现有的地图记录?

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

属性值模型

belongs_to :custom_attribute
has_many :attribute_value_maps

attribute_value_map 模型

belongs_to :product
belongs_to :custom_attribute
belongs_to :attribute_value

【问题讨论】:

  • 你能把这3个模型之间的关系代码贴出来吗?产品、custom_attribute、attribute_value

标签: ruby-on-rails forms activerecord


【解决方案1】:

如果我理解您在此处尝试执行的操作,我想您可能会为使用 ActiveRecord 带来很多痛苦。

这种动态属性是创建 NoSQL 数据库的原因。您可能需要考虑是否像 Mongoid/MongoDB 是更好的选择:

至少,您可能需要考虑查看 ActiveRecord 的序列化功能:

http://api.rubyonrails.org/classes/ActiveRecord/Base.html 看底部的序列化函数。

如果您使用的是 Postgres,您可能需要查看使用原生数据库格式的 hstore 扩展来允许对属性字段进行索引:

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

希望以上内容对您有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2016-03-23
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多