2

I have been around and around with this. Have seen similar questions here but it seems I have an extra complicating factor; what worked for them doesn't work for me.

I have models and tables for User, Group, GroupMember. A group is owned by a user, but each group can have an arbitrary number of group members, i.e., other users. Here are my associations:

In User,

has_many :groups

In Group,

belongs_to :user
has_many :group_members 
has_many :members, :class_name => "User", :through=>:group_members

In GroupMember,

belongs_to :member, :class_name=>"User"  
belongs_to :group

To get at the members of a group, then, in groups_controller.rb I do this:

@groupmembers = @group.group_members.all

However, that generates the following error:

NameError in GroupsController#show 
uninitialized constant Group::GroupMember

Like I say, I have been around and around with this... where have I gone wrong? Thanks in advance for looking...

David
  • 78
  • 1
  • 6

3 Answers3

2

I finally got this working on my own. The part I was missing was in the User class; since User is the underlying class of Member, I needed this:

belongs_to :groupmember, :foreign_key=>"member_id"

Once that was in place, Rails was able to find everything as it should, e.g,

Group.find(1).members now finds all users who belong to the group with an ID of 1.

David
  • 78
  • 1
  • 6
1

Sometimes it can also be as simple as the belongs_to :model needs to be singular instead of plural. I made this mistake on my relationship today.

1

Assuming you have a model called GroupMembers (which you should given this is a has_many through association), your non-through association should look like this on both the Group and Member models:

has_many :group_members, :class_name => "GroupMembers"

For some reason rails isn't pluralizing the second model in the association, so just do it yourself.

dsent
  • 11
  • 1
  • Thank you for answering. Unfortunately, it still raises the same error after I tried your suggestion. Some salient points: (1) I don't have a Member model; it's actually an alias of User. (2) My through association model is named GroupMember without the plural s at the end... I altered your suggestion to use GroupMember instead of GroupMembers. Still no joy. – David Oct 26 '11 at 19:34
  • For now I have been able to work around this by doing the following in my Group#show action, where I want an instance of all members in a group: '@groupmembers = Group.find_by_sql("select * from groups g join group_members gm on gm.group_id = g.id join users u on u.id = gm.member_id where g.id = #{@group.id}")' – David Oct 26 '11 at 19:35