I have three models:
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
For Site and Users, I have a join table (sites_users).
Every Site has n Users. Every Tenant has n Sites.
To get a list of users for a specific site, it’s easy:
t = Tenant.first
s = t.sites.first
s.users
But is there an association I can add to Tenant to provide a list of all users between all sites under that tenant? So that I can do:
t = Tenant.first
t.users
A number of people have asked for this, you’ll see some discussion in the Rails Lighthouse Ticket #8994 of some developers trying to merge in the functionality of the nested_has_many_through plugin. If you’re on Rails 2.3, the nested_has_many_through plugin might work for you, otherwise in Rails 3 you could write an ARel query to find the right set of studies.