This article uses Ruby 2.6.5 installed on macOS Catalina 10.15.6. There was some ambiguity about find and find_by, so I tried to summarize it myself.
find --Specify __id (primary key) __ as an argument. --The image is to get the record with the specified id. --If the id is not found, a __exception (RecordNotFound) will be returned. __ You get a red error page, right? --It is possible to specify multiple arguments.
Model name.find(id data)
――Specifically, use it as follows.
Item.find(1) # =>Returns a record with id 1
Item.find(1,3,5) # =>Returns the specified id as an array
find_by --Data can be acquired only for the first match __. --You can also use column names other than id as search conditions. --Returns nil if none match the conditions. It is convenient when you want to continue processing after the description of find_by even if there is no acquired data. --Multiple conditions can be specified.
Model name.find_by(conditions)
――Specifically, use it as follows.
Article.find_by(title: 'hoge')
# =>title is'hoge'Returns the first matching data in
Fruit.find_by(name: 'apple', color: 'red')
# =>name is'apple'And the color is'red'Returns the data of
Fruit.find_by(name: 'apple', color: 'blue') #=>Returns nil
Recommended Posts