7

我似乎无法解决名称约定或者我错误地加入它们。

这是我从用户模型中得到的错误:

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

而从公司模式来看:

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

用户.rb

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

公司.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

我一直在查找示例,但老实说,我不明白为什么它一直在爆炸。如果需要任何其他信息,我会提供,感谢您提供的任何帮助。

4

3 回答 3

6

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.

于 2013-08-22T16:47:41.527 回答
0

It should be:

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

Only last word should be pluralized

于 2013-08-22T16:47:30.303 回答
0

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
于 2013-08-22T16:48:29.337 回答