jeudi 27 août 2015

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?

Aucun commentaire:

Enregistrer un commentaire