0

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

1 回答 1

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
于 2012-09-26T10:40:36.500 回答