开发者

Rails: Why "has_many ..., :through => ..." association results in "NameError: uninitialized constant ..."

开发者 https://www.devze.com 2023-03-27 21:43 出处:网络
To express that a group can have multiple users, and a user can belong to multiple groups, I开发者_开发百科 set the following associations:

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 ?


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


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


i think change name of class UserGroups to UserGroup


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号