Differences between find, find_by, find_by_sql methods

I have come up with a similar method for advancing the learning of rails, so I would like to summarize it.

What is the find method?

It is a method` to get the record by setting ʻid of the specified model as an argument.

For example ↓↓↓

pry(main)> Tweet.find(1)
   (0.4ms)  SET NAMES utf8,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
  Tweet Load (0.3ms)  SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`id` = 1 LIMIT 1
=> #<Tweet:0x00007fa3fd3800d8
 id: 1,
 text: "aaaaa",
 image: "",
 created_at: Mon, 13 Jul 2020 06:42:56 UTC +00:00,
 updated_at: Mon, 13 Jul 2020 06:42:56 UTC +00:00,
 user_id: 1>

You can see that we were able to get the record of id1.

What is the find_by method?

It is a method` that can be obtained even under conditions other than ʻid of the specified model. (Of course, you can also search by id)

For example, looking at the record contents described above, the text column contains the value "aaaaa". I would like to get this.

pry(main)> Tweet.find_by(text: "aaaaa")
  Tweet Load (0.4ms)  SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`text` = 'dv sdvdfsv' LIMIT 1
=> #<Tweet:0x00007fa3db12bd90
 id: 1,
 text: "aaaaa",
 image: "",
 created_at: Mon, 13 Jul 2020 06:42:56 UTC +00:00,
 updated_at: Mon, 13 Jul 2020 06:42:56 UTC +00:00,
 user_id: 1>

You specify the text column as an argument and search and get the record that contains the value "aaaaa".

What is the find_by_sql method?

Method used when retrieving and retrieving data using SQL statements. When you get the record of id1


SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`id` = 1

The select statement was issued. This time I will try to get the record by assigning this statement to a variable.

pry(main)> query = "SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`id` = 1"
=> "SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`id` = 1"
[9] pry(main)> Tweet.find_by_sql(query)
  Tweet Load (0.3ms)  SELECT `tweets`.* FROM `tweets` WHERE `tweets`.`id` = 1
=> [#<Tweet:0x00007fa3bc0e36e0
  id: 1,
  text: "aaaaa",
  image: "",
  created_at: Mon, 13 Jul 2020 06:42:56 UTC +00:00,
  updated_at: Mon, 13 Jul 2020 06:42:56 UTC +00:00,
  user_id: 1>]

You have obtained it! !!

To be honest, I don't have an image when using find_by_sql, but will I use it in the future? .. .. ..

Recommended Posts

Differences between find, find_by, find_by_sql methods