When, if ever, should you use the association identifier directly?

Let's say I have a model User, a model Taskthat has the boolean attribute and a model that is created when the task completes, and belongs_to :userso :has_one :eventdoes .completedEventbelongs_to :event

In TaskObserverI noticed that instead

# 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 method seems the most correct, are there any advantages to using any of the latter options?

+3
source share
3 answers

In this particular case, I went with task.create_event(:user_id=>task.user_id). By doing:

$ rails c
ruby-1.8.7-p299 > ActiveRecord::Base.logger = Logger.new(STDOUT)
ruby-1.8.7-p299 > Task.where("user_id IS NOT NULL).user.id
...
User Load (1.2ms)  SELECT `users`.* FROM `users` WHERE (`users`.`id` = 103) LIMIT 1
=> 103

, Rails User . , , , .

, , , , , .

+1

Rails , "" "", . user_id user, - .

, , . , _ , , . ?

+2

- "" "" - , ...

task.user.id, , ; task.user_id .

  • . , , , , id , task.user_id, , . development.log....
+2

Source: https://habr.com/ru/post/1777202/


All Articles