2012-04-20 50 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