Mohamed Emad Hegab
Mohamed Emad Hegab

Reputation: 2675

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?

Upvotes: 0

Views: 4334

Answers (2)

Mohamed Emad Hegab
Mohamed Emad Hegab

Reputation: 2675

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

belongs_to :user
belongs_to :role

I left out the colons.

Upvotes: 1

usha
usha

Reputation: 29369

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.

Upvotes: 2

Related Questions