I have 3 different Models
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
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:
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:
for this to work you should have
groupsassociation in your User model.It is also unclear for me why you have
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: