7

我有問題建立一個協會是一個has_many :through與條件。我有這個模型:Rails has_many:通過條件和建築協會

class Contact < AR 
    has_many :group_contacts 
    has_many :groups, :through => :group_contacts, :conditions => {:groups => {:published => true}} 
end 

當我嘗試從聯繫人實例化組時發生問題。有了上面的語法,我得到一個錯誤:

contact.groups.build 
=> ActiveRecord::UnknownAttributeError: unknown attribute: groups 

但是當我使用下面的語法它的工作原理:

has_many :groups, :through => :group_contacts, :conditions => ['groups.published = ?', true] 

contact.groups.build 
=> #<Group id: nil, name: nil, description: nil, created_at: nil, updated_at: nil, published: true> 

我看到this question到確切的問題提供參考。據說一張票將被歸檔爲這個bug(回到前導3版本)。 rails 3.0.x我找不到任何東西。

我使用的是3.0.8。有沒有人發現這個問題?

其它注意事項

我還發現,當我建羣,它建立在實際忽略在關聯我的條件。我上面的版本有published => true的唯一原因是因爲它是數據庫中的默認值。

這似乎是一個迴歸,任何人都可以驗證這一點嗎?

+1

難道你的意思是:'的has_many:羣體:通過=>:group_contacts,:條件=> {:組=> {:發佈=>真}}' ? – dwhalen

+0

oops,thx很好找! – brad

回答

9
has_many :groups, :through => :group_contacts, :conditions => {:published => true} 

has_many :groups, :through => :group_contacts, :conditions => {"groups.published" => true} 
+0

啊對...我完全習慣於在其他加入的模型上有條件,例如':conditions => {:some_model => {:attr => true}}',但是我猜想當條件在實際的' has_many'模型,你不需要指定它。謝謝 – brad