简体   繁体   English

将JOIN查询转换为Rails Active Record关联

[英]Translating JOIN Query into Rails Active Record Associations

I have 3 different Models 我有3种不同的型号

class GroupMember < ActiveRecord::Base
attr_accessible :group_id, :user_id, :owner_id
has_one :user
end

class Group < ActiveRecord::Base
attr_accessible :name, :owner, :permission
has_many :groupMembers
end

class User < ActiveRecord::Base
end

and when im in the groups_controller.rb i want realize the following query with associations 当我在groups_controller.rb中时,我想实现以下带有关联的查询

SELECT * FROM groups 
LEFT JOIN  group_members ON groups.id = group_members.group_id 
LEFT JOIN users ON group_members.user_id = users.id WHERE users.id = 1

or the joins query 或联接查询

Group.joins('LEFT JOIN  group_members ON groups.id = group_members.group_id LEFT JOIN users ON group_members.user_id = users.id').where('users.id = ?', current_user.id );

Is this possible? 这可能吗?

 Group.joins(:user_id => current_user.id)

I believe it is possible but it is a bit difficult to test as soon as I don't have a DB with these tables. 我相信有可能,但是一旦我没有这些表的数据库,就很难进行测试。 Probably something like: 大概是这样的:

Groups.joins(:group_members, :user).merge(User.where(:id => current_user.id))

But the design is a bit strange. 但是设计有点奇怪。 I suppose you want to fetch all groups for a certain user, and it is best put like this: 我想您想为某个用户获取所有组,最好这样放置:

@user = User.find_by_id(current_user.id)
@groups = @user.groups

for this to work you should have groups association in your User model. 为此,您应该在用户模型中具有groups关联。

It is also unclear for me why you have GroupMember has_one :user . 对我来说还不清楚为什么会有GroupMember has_one :user I understand that group member is related to only one user, but can a user be represented as several group members, of different groups? 我了解该组成员仅与一个用户相关,但是可以将一个用户表示为不同组的多个组成员吗? If yes, the Rails way to design it would be: 如果是,Rails的设计方式将是:

class GroupMember < ActiveRecord::Base
  attr_accessible :group_id, :user_id, :owner_id
  belongs_to :user
  belongs_to :group
end

class Group < ActiveRecord::Base
  attr_accessible :name, :owner, :permission
  has_many :group_members
  has_many :users, :through => :group_members
end

class User < ActiveRecord::Base
  has_many :group_members
  has_many :groups, :through => :group_members
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM