【发布时间】: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