【问题标题】:Querying ActiveRecord through associations通过关联查询 ActiveRecord
【发布时间】:2011-07-14 22:01:08
【问题描述】:

我有一个用户模型和组模型。用户 has_and_belongs_to_many :groups 和组 has_and_belongs_to_many :users。

我想使用 ActiveRecord 来查询某个用户所在的所有组中的所有用户。我可以通过@user.groups 获取所有组并手动将@user.groups.members 连接在一起,消除重复我可以找到(一个用户可能与另一个用户在多个组中,但我只想要另一个用户的名字一次)。

但是有没有更好的方法呢?

【问题讨论】:

  • 您能发布您的实际型号代码吗?很难判断你是在使用belongs_to,还是has_and_belongs_to_many,还是别的什么。
  • 糟糕,抱歉。更新了问题。他们都使用 has_and_belongs_to_many。

标签: ruby-on-rails activerecord associations


【解决方案1】:

你应该可以做这样的事情:

User.includes(:groups).where("groups.id in (?)", @user.group_ids)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 2010-10-15
    • 2023-03-11
    相关资源
    最近更新 更多