Ruby on rails 写信给你有很多:通过联系和回调

Ruby on rails 写信给你有很多:通过联系和回调,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,考虑一个“Name”模型,该模型具有必需的“label”属性和具有以下关联的任意Rails 3模型“Foo”: has_many :names, :dependent => :destroy has_many :special_names, :through => :names, :source => :label, :conditions => { 'special_names.label' => 'special' }, :dependent => :de

考虑一个“Name”模型,该模型具有必需的“label”属性和具有以下关联的任意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无法从条件推断“special names”关联的所有成员的“label”属性都需要设置为“special”

我尝试使用“add_before”关联回调,但连接模型从未调用过该回调(而是使用“:source”和“Foo”)

关于如何在模型中处理这个问题有什么想法吗(与之相反:在控制器中使用特殊逻辑来处理这个问题-我目前就是这样处理的)

编辑:(关于来自的答案)

所表达的关系实际上是一种“有很多:通过”的关联。我会再试一次,这次我会举一个(希望)更好的例子:

# 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

如果我上面的评论是正确的,并且您没有执行
has\u many:to
,则此操作有效:

has_many :special_names, :class_name => 'Name', :conditions => {:label => 'special'}, :dependent => :destroy
所以现在你可以做了

foo = Foo.create
foo.special_name.build
ActiveRecord
将正确实例化您的特殊名称,并使用
标签
属性,该属性的值为
“special”
,我找到了解决方案(谢谢x0f@Freenode)-需要将“特殊”协会一分为二<代码>有很多:特殊的用户标签,:通过=>:user标签,:source=>:label,:conditions=>{'user\u labels.descriptor'=>'special'},:dependent=>:destroy成为

1)
有很多:特殊标签,:class\u name=>'UserLabel',:conditions=>{:descriptor=>'special'},:dependent=>:destroy

2)
有很多:特殊用户标签,:通过=>:special标签,:source=>:label,:dependent=>:destroy


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

当你说写时,你的意思是类似于,
foo.special\u names.build
?这个
有多少:通过
?这不就是一个有很多条件的
吗?jpemberthy:是的-具体来说,我想用与hbtm关联(…\ID)相同的方式使用表单属性和质量分配。我在我原来的问题中添加了另一个例子-感谢后续!