Alaude_
Alaude_

Reputation: 71

Rails: NameError: uninitialized constant on join table

I can't seem to work around the name convention or if I'm joining them incorrectly.

This is the error I'm getting from the user model:

> user.companies
NameError: uninitialized constant User::CompaniesUser

And from the company model:

> company.users
NameError: uninitialized constant Company::CompaniesUser

user.rb

has_many :companies_users
has_many :companies, :through => :companies_users

company.rb

has_many :companies_users
has_many :users, :through => :companies_users

company_user.rb

class CompanyUser < ActiveRecord::Base
  belongs_to :company
  belongs_to :user
end

I've been looking up through examples but I honestly don't understand why it keeps exploding. If there's any additional information needed, I'll provide it, I appreciate any help given.

Upvotes: 7

Views: 4440

Answers (3)

vee
vee

Reputation: 38645

Your association companies_users will be mapped to class named CompaniesUser by Rails because "companies_users".classify will give you CompaniesUser. But the class you want to associate is CompanyUser, so the solution in this case would be to modify your associations to include class_name option as follows:

# user.rb

has_many :companies_users, class_name: CompanyUser
has_many :companies, :through => :companies_users

# company.rb

has_many :companies_users, class_name: CompanyUser
has_many :users, :through => :companies_users

Update: This is of course if you want to stick with the association name companies_users, otherwise @Babur has a solution for you.

Upvotes: 6

Holger Just
Holger Just

Reputation: 55778

Because of your has_many :companies_users in your Company model, Rails tried to load a model class for that table, that be convention would be called CompaniesUser. To make your code work, you could either change your has_many declaration to

has_many :company_users

or even get rid of the CompanyUser model completely and use has_and_belongs_to_many instead.

class User
  has_and_belongs_to_many :companies
end

class Company
  has_and_belongs_to_many :users
end

Upvotes: 0

Babur Ussenakunov
Babur Ussenakunov

Reputation: 1995

It should be:

has_many :company_users
has_many :companies, :through => :company_users

Only last word should be pluralized

Upvotes: 0

Related Questions