Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Why "has_many ..., :through => ..." association results in "NameError: uninitialized constant ..."

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 ?

like image 563
Misha Moroshko Avatar asked Aug 12 '11 12:08

Misha Moroshko


2 Answers

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

like image 85
Skilldrick Avatar answered Oct 15 '22 13:10

Skilldrick


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

like image 45
Femaref Avatar answered Oct 15 '22 12:10

Femaref