【问题标题】:Rails - newbie association question with both has_many and HABTM modelsRails - has_many 和 HABTM 模型的新手关联问题
【发布时间】:2010-11-01 01:23:28
【问题描述】:

我有三个模型:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢,帕特里克!那张灯塔门票令人鼓舞。我会考虑为权宜之计编写一个 ARel 查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    相关资源
    最近更新 更多