将JOIN查询转换为Rails活动记录关联

时间:2012-09-26 08:45:42

标签: ruby-on-rails associations

我有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

当我在 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

或联接查询

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 );

这可能吗?

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

1 个答案:

答案 0 :(得分:0)

我相信这是可能的,但是一旦我没有这些表格的数据库就很难进行测试。可能类似于:

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

但设计有点奇怪。我想你想为某个用户获取所有组,最好是这样:

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

要使其工作,您的用户模型中应该有groups关联。

我也不清楚为什么你有GroupMember has_one :user。我理解组成员只与一个用户相关,但是用户可以表示为不同组的多个组成员吗?如果是,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