Let's suppose I have the following models:
Group
has_many :users
User
belongs_to :group
And I have the following tables:
User_id Group
-------------------------------------
1 Police
2 Fire
3 Military
4 Police
5 Police
1 Fire
Most users belong to a single group, but some users, like user_id: 1
belongs to multiple groups. (He belongs to Police
and Fire
.
My question is: If I am given two user_id's
, (say 1
and 2
), how would I query to find out the common group that these 2 users belong to (eg, in the case above, the query would return Fire
.
Hope this makes sense.
First of all I would recommend using a has_and_belongs_to_many relationship between User and Group:
class Group
has_and_belongs_to_many :users
end
class User
has_and_belongs_to_many :users
end
You'd have tables like:
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
This would prevent the repetition you have going on in the group field in the groups table currently. It would also help avoid certain data entry errors (spelling errors) and make building a better UI easier. There are other ways to overcome these same hurdles, but they take much more effort than is saved by not following the convention usually.
Then you can get the intersection of the groups for two users (user_a and user_b) like:
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.
这实际上取决于您的关联是如何设置的,但这是在一个查询中执行此操作的一种方法
user_a.groups.where(id: user_b.groups.select(:id))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.