Rails - ActiveRecord - 基于共性寻找共同组

问题描述 投票:0回答:2

假设我有以下模型。

Group
  has_many :users

User
  belongs_to :group

我有以下表格

   User_id                    Group
  -------------------------------------
    1                        Police
    2                        Fire
    3                        Military
    4                        Police
    5                        Police
    1                        Fire

大多数用户都属于一个组,但有些用户,比如说 user_id: 1 属于多个群体。(他属于 PoliceFire.

我的问题是:如果给我两个 user_id's,(比如 12),我将如何查询这2个用户所属的共同组(例如,在上面的例子中,查询将回到 Fire.

希望这有意义。

ruby-on-rails activerecord
2个回答
0
投票

首先我建议在User和Group之间使用has_and_belongs_to_many关系。

class Group
    has_and_belongs_to_many :users
end

class User
    has_and_belongs_to_many :users
end

你会有这样的表:

create_table "groups", force: true do |t|
    t.string name
end

create_table "users", force: true do |t|
    ...
end

create_table "groups_users", id: false, force: true do |t|
    t.integer "group_id"
    t.integer "user_id"
end

这将防止你在群组表的群组字段中出现重复的情况. 它还将有助于避免某些数据输入错误(拼写错误),并使构建一个更好的UI变得更容易。还有其他方法可以克服这些同样的障碍,但它们所花费的精力比通常不遵循惯例所节省的要多得多。

然后你可以得到两个用户(user_a和user_b)的组的交集,比如。

user_a.groups & user_b.groups # => an array of the groups that they both belong to

(user_a.groups & user_b.groups).collect(&:name) # => an array of the names of the groups they both belong to.

0
投票

这真的取决于你的关联是如何设置的, 但这里有一种方法可以在一个查询中实现它.

user_a.groups.where(id: user_b.groups.select(:id))
© www.soinside.com 2019 - 2024. All rights reserved.