0

我有三个型号:Rails的 - 既和的has_many HABTM模型新手关联问题

class Tenant < ActiveRecord::Base 
    has_many :sites 
end 

class Site < ActiveRecord::Base 
    belongs_to :tenant 
    has_and_belongs_to_many :users 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :sites 
end 

对于网站和用户,我有一个连接表(sites_users)。

每个网站都有N个用户。每个租户都有n个网站。

要获得用户的列表特定网站,它很简单:

t = Tenant.first 
s = t.sites.first 
s.users 

但有一个协会,我可以添加到租客提供该租户的所有网站之间的所有用户的列表?所以,我可以这样做:

t = Tenant.first 
t.users 

回答

0

许多人问这个,你会看到一些开发商试图在nested_has_many_through plugin的功能合并Rails Lighthouse Ticket #8994一些讨论。如果你on Rails的2.3,在nested_has_many_through plugin可能为你工作,否则在Rails 3中,你可以写一个ARel查询找到合适的系列研究。

+0

谢谢,帕特里克!那个灯塔票是令人鼓舞的。我会考虑编写一个ARel查询以获得权宜之计解决方案。 – 2010-11-01 04:28:35