2011-04-12 50 views
1

考慮具有必需的「標籤」屬性和任意的Rails 3模式「富」與下列協會「名稱」的模式:寫HAS_MANY:通過協會和回調

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

現在是可能的訪問讀取關聯的「special_names」屬性,但寫入使其失敗,因爲AR無法從「條件」中爲所有「特殊名稱」成員設置「標籤」屬性需要設置爲「特殊」協會。

我試圖使用「add_before」關聯回調,但永遠不會用連接模型調用(而是使用「:source」和「Foo」)。

有關如何在模型中處理此問題的任何想法(而不是:在控制器中使用特殊邏輯來處理此問題 - 這就是我目前的處理方式)?

編輯:(關於從Ray Baxter答案)

的關係表示實際上是一個 「的has_many:通過」 關聯。我再試一次,這次(希望)更好的例子:

# 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 
+0

當你說寫作,你的意思是,像'foo.special_names.build'? – jpemberthy 2011-04-12 17:24:13

+0

這是一個'has_many:through'嗎?這不就是一個有條件的'has_many'嗎? – 2011-04-12 18:17:59

+0

jpemberthy:是的 - 我特別想用與hbtm關聯(..._id)相同的方式使用表單屬性和質量分配。 – yawn 2011-04-14 08:06:24

回答

0

我找到了解決方案(謝謝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

Works的讀取&寫入以及無縫替代(作用域)hbtm關聯。

2

如果我的上述評論是正確的,你是不是做一個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。

+0

我在原來的問題中增加了另一個例子 - 感謝後續! – yawn 2011-04-14 08:17:14