[Ruby] Differences between find, find_by, find_by_sql methods

1 minute read

A similar method came out in the progress of learning rails, so I will summarize it.

What is ##find method

It is a method that fetches records by setting the specified model’s id 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 got the record with id1.

What is find_by method?

It is a method that can be acquired even under conditions other than the specified model’s id. (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 want 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 have specified the text column as an argument and searched for the record containing the value “aaaaa”.

What is find_by_sql method?

This is the method to use when searching and retrieving data using an SQL statement. When you get the record of id1


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

The select statement was issued. This time I’ll assign this statement to a variable and get a record.

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 acquired it! !!

To be honest, I don’t have an image of using find_by_sql, but is there anything I will use it in the future? .. .. ..

Tags: ,

Updated: