Rails:为什么“has_many…:through =>…”关联结果是“NameError: uninitialized constant…”

时间:2022-03-25 19:28:31

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 ?

我做错了什么?

4 个解决方案

#1


29  

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

类UsersGroups应该是类UsersGroup。ActiveRecord模型是单数的——表是复数。

#2


1  

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

ActiveRecord尝试将名称单列出来,但您的类实际上被命名为UserGroups。重命名UserGroup。模型是奇异的。

#3


1  

i think change name of class UserGroups to UserGroup

我想把类UserGroups改成UserGroup

#4


-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

此外,请注意模型的文件名必须也是单数形式。在这种情况下,应用程序/模型/ user_group.rb

#1


29  

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

类UsersGroups应该是类UsersGroup。ActiveRecord模型是单数的——表是复数。

#2


1  

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

ActiveRecord尝试将名称单列出来,但您的类实际上被命名为UserGroups。重命名UserGroup。模型是奇异的。

#3


1  

i think change name of class UserGroups to UserGroup

我想把类UserGroups改成UserGroup

#4


-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

此外,请注意模型的文件名必须也是单数形式。在这种情况下,应用程序/模型/ user_group.rb