moeabdol
moeabdol

Reputation: 5059

Can't Access has_many Association in Rails

If a user has_many roles

has_many :roles

and a role belongs to user

belongs_to :user

then why

role.user ||= User.create(name: "moeabdol")

doesn't build the associaition between user and role

irb> role
user_id: 1
type: "admin"

irb> role.user
id: 1
name: "moeabdol"

and now this

irb> me = role.user
irb> me.roles
[]

returns an empty array!

Is this the expected behaviour? And if so then how can I build the association given that I have to create the role before the user?

Upvotes: 0

Views: 171

Answers (1)

Nimir
Nimir

Reputation: 5839

role.user ||= User.create(name: "moeabdol")

will only create a new user and assign in to the memory object, but your role object will still have a nil value in user_id

What you need is something like:

role.user ||= role.create_user(name: "moeabdol")

create_user is one of the belongs_to association method (look for create_association(attributes = {}) here)

Upvotes: 1

Related Questions