thank_you
thank_you

Reputation: 11107

Referencing Associated Object Returns Nil

I have two models.

class User < ActiveRecord::Base
  has_one :message
end

class Message < ActiveRecord::Base
  belongs_to :user
end

If I have a created user with an associated Message and I delete that message and create a new one like, user.message returns nil. For example.

user = User.create

message = Message.create(user_id: user.id)

Message.where(user_id: user.id).destroy_all

Message.create(user_id: user.id)

# Now if I call this below, it always returns nil
user.message

Why does this occur? Shouldn't Rails 3 pick up on that change? How do I fix this?

Upvotes: 0

Views: 33

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Just load the object again before doing user.message like, user.reload.

reload - Reloads the record from the database.

Upvotes: 1

Related Questions