Help us understand the problem. What is going on with this article?

【Rails】find_by 引数にはインスタンス変数?明示した引数?

More than 1 year has passed since last update.

find_byには、
インスタンス変数を引数に渡すのか?(記述量は少なくなる)
明示してID(対象カラム)を渡すのか?

結論から

指定するシンボルと渡す引数を明確にしよう!!

answer.rb
@memo = Memo.find_by(child_id: @child.id, facility_id: @reservation.facility_id)

安定&&最速

検証(雑)

※2~3回しか試してないです。

sample.rb
@memo = Memo.find_by(child: @child, facility: @reservation.facility)
irb(main):010:0> @memo        = Memo.find_by(child: @child, facility: @reservation.facility)
  Facility Load (0.2ms)  SELECT  `facilities`.* FROM `facilities` WHERE `facilities`.`id` = 2 LIMIT 1
  Memo Load (0.4ms)  SELECT  `memos`.* FROM `memos` WHERE `memos`.`child_id` = 7 AND `memos`.`facility_id` = 2 LIMIT 1

0.6m

sample.rb
@memo = Memo.find_by(child_id: @child.id, facility_id: @reservation.facility_id)
irb(main):011:0> @memo        = Memo.find_by(child_id: @child.id, facility_id: @reservation.facility_id)
  Memo Load (0.3ms)  SELECT  `memos`.* FROM `memos` WHERE `memos`.`child_id` = 7 AND `memos`.`facility_id` = 2 LIMIT 1

0.3m ~ 0.4m

sample.rb
@memo = Memo.find_by(child: @child, facility: @reservation.facility_id)
irb(main):016:0>     @memo        = Memo.find_by(child: @child, facility: @reservation.facility_id)
  Memo Load (0.6ms)  SELECT  `memos`.* FROM `memos` WHERE `memos`.`child_id` = 7 AND `memos`.`facility_id` = 2 LIMIT 1
=> #<Memo id: 1, child_id: 7, facility_id: 2, content: "こんにちは", created_at: "2018-11-24 13:17:02", updated_at: "2018-11-24 13:17:11">

0.5m ~ 0.6m

sample.rb
@memo = Memo.find_by(child_id: @child, facility_id: @reservation.facility_id)
  Memo Load (0.4ms)  SELECT  `memos`.* FROM `memos` WHERE `memos`.`child_id` = 7 AND `memos`.`facility_id` = 2 LIMIT 1
=> #<Memo id: 1, child_id: 7, facility_id: 2, content: "こんにちは", created_at: "2018-11-24 13:17:02", updated_at: "2018-11-24 13:17:11">

0.3m ~ 0.9m

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away