Rails: Why “has_many …, :through => …” association results in “NameError: uninitialized constant …”

北城以北 提交于 2019-12-20 18:03:11

问题


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 ?


回答1:


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




回答2:


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




回答3:


i think change name of class UserGroups to UserGroup




回答4:


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



来源:https://stackoverflow.com/questions/7040022/rails-why-has-many-through-association-results-in-nameerror-un

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!