Rails - 与has_many和HABTM模型的新手关联问题

时间:2010-11-01 01:23:28

标签: ruby-on-rails activerecord associations has-and-belongs-to-many has-many

我有三种模式:

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

1 个答案:

答案 0 :(得分:0)

有很多人要求这样做,你会看到一些开发人员Rails Lighthouse Ticket #8994试图合并nested_has_many_through plugin的功能。如果您使用的是Rails 2.3,nested_has_many_through plugin可能适合您,否则在Rails 3中您可以编写ARel查询以查找正确的研究。