2012-04-20 90 views
0

我有這個relationsship在many_to_many關聯中作用範圍?

class House 
has_many :apartments 
end 

class Apartments 
belongs_to :house 
has_many :category_join_table 
has_many :categories, :through => :category_join_table 
end 

我在我的房子模型的目的作出了範圍方法「只顯示與租房」

scope :with_apartments, lambda { joins(:appartments).group('appartments.id').uniq { |h| h[:id] }} 

所以我可以在控制器邏輯house.with_apartments 。這工作正常,所以我只得到與頁面上的公寓房子。沒有公寓的房子沒有顯示。

但現在我想做一個關聯到我的分類模型(many_to_many)。所以「只顯示與公寓和類別= X家」

+0

澄清你的問題:你正在努力實現以下靈活性:'@ some_category.houses'? – jdoe 2012-04-20 09:09:46

+0

是的。與房屋協會。在我的模板頁面上,如果有這個 - @ houses.each do | house | - house.appartments.each do | a | #{a.guests} – Remco 2012-04-20 09:11:46

+0

您可以像這樣加入多個關聯,連接(:appartments =>:categories),然後附加一些查詢。 – Yanhao 2012-04-20 09:27:29

回答

2

試試這個:

# in category.rb 

has_many :category_join_table 
has_many :apartments, :through => :category_join_table 
has_many :houses, :through => :apartments 
+0

謝謝Jdoe。你能幫助我如何根據你的關係編寫範圍方法嗎? – Remco 2012-04-20 09:28:47

+0

要做什麼?因爲你的問題是:「只顯示公寓和類別= X的房子」。要做到這一點使用:'Category.find(some_id).houses'。 – jdoe 2012-04-20 09:45:52

+0

我試過這個..scope:with_appartments_and_agri,lambda {joins(:appartments).group('appartments.id')。uniq {| h | h [:id]} joins(:appartments =>:categories).where(「categories.name ='Agriturismo'」)}} 但我沒有工作... – Remco 2012-04-20 09:50:19