简体   繁体   English

ruby:NameError:未初始化的常量

[英]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中调用它的方法

before_create :build_role

def build_role
  memberships.build
end

it gives me 它给我

uninitialized constant User::Membership 未初始化的常量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 Membership

belongs_to :user
belongs_to :role

I left out the colons. 我省略了冒号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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