14

To express that a group can have multiple users, and a user can belong to multiple groups, I set the following associations:

class Group < ActiveRecord::Base
  has_many :users_groups
  has_many :users, :through => :users_groups
end

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

class UsersGroups < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

However, when I type:

Group.find(1).users

I get:

NameError: uninitialized constant Group::UsersGroup

What am I doing wrong ?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

4 Answers4

29

class UsersGroups should be class UsersGroup. ActiveRecord models are singular - the tables are plural.

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
Skilldrick
  • 69,215
  • 34
  • 177
  • 229
  • Thanks! It just looks strange/wrong to me to have a model called `UsersGroup`. I don't want one of them to be plural and the other singular. Maybe I should rename the model to something like UserGroupPair, so that the table name will be `user_group_pairs`. What do you think ? – Misha Moroshko Aug 12 '11 at 12:42
  • 1
    When you have a join model, the standard practice is to come up with a word that describes the association. For example, GroupMembership or something. Just to check though, are you sure you need a join model? You can get away with just a table if the join doesn't need logic. – Skilldrick Aug 12 '11 at 12:53
  • Do you mean model name `GroupMembership` and table name `group_membership`, i.e. both singular ? I'm not sure I understood your second point regarding getting rid of the join table. Could you elaborate a bit ? – Misha Moroshko Aug 12 '11 at 13:20
  • If you don't like inconsistency then call the join model UserGroup - that would be normal for a rails project. You'd have to rename the table to user_groups too. – Simon Aug 12 '11 at 13:24
  • @Misha You can get rid of the model but keep the table. But if you need the model, call it `GroupMembership` and the table `group_memberships`. – Skilldrick Aug 12 '11 at 13:26
  • @Misha [See this for a discussion of many-to-many relationships](http://blog.hasmanythrough.com/2007/1/15/basic-rails-association-cardinality). – Skilldrick Aug 12 '11 at 13:27
  • @Skilldrick Thanks! Now I understand what you meant. – Misha Moroshko Aug 12 '11 at 13:32
  • Hi Skilldrick, does the plurality of the model name also have to correspond to the name of the file? I.e. users_group.rb? – Noz Oct 02 '12 at 23:29
1

ActiveRecord tries to singularize the name, but your class is actually named UserGroups. Rename it to UserGroup. The models are singular.

Femaref
  • 60,705
  • 7
  • 138
  • 176
1

i think change name of class UserGroups to UserGroup

Dnyan Waychal
  • 1,418
  • 11
  • 27
-1

In addition, please note that the filename of the model must also be in the singular form. In this case, app/models/user_group.rb