【问题标题】:has_many association with conditions on ActiveRecordhas_many 与 ActiveRecord 上的条件的关联
【发布时间】:2012-07-04 16:09:44
【问题描述】:

我有这个模型:StoreAddress

第二个模型Address我正在将它与其他模型一起使用,并且里面有一些针对不同模型的自定义字段。

是的,就像多态但没有 varchar 类的字段,我使用的是整数。 (优化的东西)

现在在我的Store 模型上,集合中的关联如下:

class Store < ActiveRecord::Base
    has_many :addresses, :foreign_key => "parent_id", :conditions => ['parent_kind = ?', 2]
    accepts_nested_attributes_for :addresses
end 

现在在我的控制器中我这样做了:

@store.addresses.build

我可以在表单中使用f.fields_for :addresses...

当我提交表单并将数据保存到数据库时出现问题。

stores 表中的记录被保存,addresses 中的记录与存储的parent_id 一起保存,但parent_kind0 中,这是该值的默认值MySQL 上的属性。

我的快速修复是这样的:

@store = Store.new(params[:store])
    @store.addresses[0].parent_kind = 2
    if @store.save
    ....

但我知道肯定有其他方法。

有什么建议吗?

谢谢。

【问题讨论】:

    标签: ruby-on-rails-3 activerecord associations polymorphic-associations


    【解决方案1】:

    您是否尝试在嵌套表单中使用隐藏字段?

    <%= f.fields_for :addresses, Address.new do |ff| %>
      <%= ff.hidden_field :parent_kind, :value => 2 %>
      ...
    

    编辑

    如果您出于安全考虑不想使用它,这里有另一种可能会有所帮助的方法。您可以尝试像这样使用association callback

    class Store < ActiveRecord::Base
      has_many :addresses, :foreign_key => "parent_id", 
                           :conditions => ['parent_kind = ?', 2],
                           :before_add => Proc.new { |store,address| address.parent_kind = 2}
      accepts_nested_attributes_for :addresses
    end 
    

    【讨论】:

    • 谢谢,这会起作用,但bad people 仍然可以在发送帖子之前覆盖隐藏字段。
    猜你喜欢
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多