dennismonsewicz
dennismonsewicz

Reputation: 25552

Rails 4: has_many :through errors

Here is my join model:

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

My User model:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  ROLES = %w[admin requestor requestor_limited shipping_vendor].freeze

  attr_accessor :temp_password

  has_many :companies_users

  ...

end

If I run this in the console:

u = User.first
u.companies

This is the error I am getting:

NameError: uninitialized constant User::CompaniesUser

Upvotes: 0

Views: 69

Answers (3)

Breen ho
Breen ho

Reputation: 1631

has_many through relationships should be like this:

In app/models/company.rb file,

  has_many :company_users
  has_many :users, :through => :company_users

In app/models/user.rb file,

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

In app/models/company_user.rb file,

  belongs_to :company
  belongs_to :user

If you want to delete the dependent records in company_users table when deleting companies/users,

Add, , :dependent => :destroy at the end of has_many relations in Company and User model.

Hope this helps you..

Thanks.!!

Upvotes: 4

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16514

The model shall be either:

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

Or has_many declaration sheel be defined explicitly as:

class User < ActiveRecord::Base
   has_many :company_users
end

Upvotes: 1

Nithin
Nithin

Reputation: 3699

it must be

has_many :company_users

"CompanyUser".tableize => "company_users"

Upvotes: 3

Related Questions