Say I have a User model, a Task model that belongs_to :user, :has_one :event, has a completed boolean attribute, and an Event model that is created when a task is completed, and also belongs_to :event.
In the TaskObserver I’ve noticed that instead of
# app/controllers/task_observer.rb
class TaskObserver < ActiveRecord::Observer
def after_update(task)
def after_update
task.create_event(:user=>task.user) if task.completed?
end
end
I could write
task.create_event(:user_id=>task.user.id)
or even
task.create_event(:user_id=>task.user_id)
While the first way seems the most correct, are there benefits to using either of the latter variations?
In this specific case I went with
task.create_event(:user_id=>task.user_id). By running:you can see that Rails will actually load the
Userfrom the database. Even if it was cached, I don’t see why I should handle the actual objects if I’m just copying a reference.So in general, I think it’s preferred to use objects when you’ve used them before, and IDs when you didn’t and don’t plan to.