【问题标题】:Writing to has_many :through associations and callbacks写入 has_many :通过关联和回调
【发布时间】:2011-04-12 16:48:13
【问题描述】:

考虑一个具有必需“label”属性的“Name”模型和具有以下关联的任意 Rails 3 模型“Foo”:

has_many :names, :dependent => :destroy
has_many :special_names, :through => :names, :source => :label, :conditions => { 'special_names.label' => 'special' }, :dependent => :destroy

现在可以访问“special_names”属性以读取关联,但写入失败,因为AR无法从“label”属性的条件推断需要为“特殊名称”关联的所有成员设置为“特殊”。

我尝试使用“add_before”关联回调,但连接模型永远不会调用它(而是使用“:source”和“Foo”)。

关于如何在模型中处理这个问题的任何想法(而不是:在控制器中使用特殊逻辑来处理这个 - 这就是我目前的处理方式)?

编辑:(关于Ray Baxter的回答)

表达的关系实际上是一个“has_many :through”关联。我会再试一次,这次是(希望)更好的例子:

# Label is a shared entity which is used in many contexts
has_many :labels, :through => :user_labels

# UserLabel is the join model which qualifies the usage of a Label
has_many :user_labels, :dependent => :destroy

# special_user_labels is the topic of this question
has_many :special_user_labels, :through => :user_labels, :source => :label, :conditions => { 'user_labels.descriptor' => 'special' }, :dependent => :destroy

【问题讨论】:

  • 当你说写作时,你的意思是,foo.special_names.build
  • 这个has_many :through 怎么样?这不就是带条件的has_many吗?
  • jpemberthy:是的 - 具体来说,我想以与 hbtm 关联 (..._ids) 相同的方式使用表单属性和批量分配。

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

如果我上面的评论是正确的,而你没有做 has_many :through,这有效:

has_many :special_names, :class_name => 'Name', :conditions => {:label => 'special'}, :dependent => :destroy

所以现在你可以做

foo = Foo.create
foo.special_name.build

并且ActiveRecord 将正确地使用具有值"special"label 属性实例化您的special_name。

【讨论】:

  • 我在原始问题中添加了另一个示例 - 感谢您的跟进!
【解决方案2】:

我找到了解决方案(感谢 x0f@Freenode)——需要将“特殊”关联一分为二。 has_many :special_user_labels, :through => :user_labels, :source => :label, :conditions => { 'user_labels.descriptor' => 'special' }, :dependent => :destroy变成了

1)has_many :special_labels, :class_name => 'UserLabel', :conditions => { :descriptor => 'special' }, :dependent => :destroy

2)has_many :special_user_labels, :through => :special_labels, :source => :label, :dependent => :destroy

适用于读写以及无缝替代(范围)hbtm 关联。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 2015-01-27
    相关资源
    最近更新 更多