简体   繁体   中英

ruby : NameError: uninitialized constant

i have the following problem

i have the following association between user and role models

# User
has_many :memberships
has_many :roles , :through =>  :memberships

# Role
has_many :memberships
has_many :users , :through =>  :memberships

and i have bridge caled membership as you can guess it have

# Membership
belongs_to user
belongs_to role

the problem is when i try to create new user i have this method that i call it in before_create

before_create :build_role

def build_role
  memberships.build
end

it gives me

uninitialized constant User::Membership

what should i do to overcome this?

Specify the class name explicitly in your association definition

has_many :memberships, :class_name => "Membership"
has_many :roles , :through =>  :memberships

Generally its not needed if you follow the naming convention for associations. It may be because you have your models namespaced.

OK, I found the problem… totally my fault. In Membership , it should be

belongs_to :user
belongs_to :role

I left out the colons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM