** Day 23 of Calendar Planning 2020 ** It's been about 3 months since I started studying programming, so I will leave a note of what I learned in the article as an output. I would be happy if I could help anyone entering the world of programming. Please let me know if there are any words that are wrong, wrong, or misunderstood ^^ I'm sorry if it's hard to read the words for a long time. I will do my best to get used to it little by little.
It is the content that I personally did not understand and investigated and interpreted in my own way. I think there are many other articles that are detailed, so I wonder if you can think about it as a general outline here ^^; (Even if you write in detail, it will be a copy and paste at some point ^^;)
find, find_by, where These are the understandings necessary to retrieve only the necessary information from the DB (database). If you want to create a web application, use one of them.
(Search is my interpretation. Please note)
Method | Search range | Data to be acquired |
---|---|---|
find | id | One |
find_by | Specified column | First one |
where | Specified column | all |
find
I remember this much ↓ ** Get one record found by specifying id (primary key). ** **
If not found, you will get the error ActiveRecord :: RecordNotFound
.
#Instance variables=Model name.find (primary key)
@post = Post.find(params[:id])
I will describe it like this.
The part contains 1 or 2 or 3, ,,, n in id and gets the one related to it. If it is 1, => post.find (1) and get the data of id: 1 of post.
find_by
I remember this much ↓ ** You can specify columns other than id with + α for the role of find **
In find, the columns that can be specified (searchable) were limited to id. find_by can be specified (searchable) columns other than id are OK.
The same 1 record found as the search result will be fetched. You can also specify characters, but only the first one you find will be applied.
#Model name.find_by(Arbitrary column name:Stored value)
@post = Post.find_by(title: "Qiita")
Get one that stores "Qiita" in the title column of Post.
Use find to find by id Otherwise use find_by
where
I remember this much ↓ ** There are multiple records to be acquired by + α in the role of find_by. ** **
where can be specified (searchable) in the same way as find_by Columns other than id are OK
Search results are all applicable, not just one.
#Model name.where(Arbitrary column name:Stored value)
@post = Post.where(title: "Qiita")
In find_by, there was one with "Qiita" in the title, Where will get everything that has "Qiita" in the title.
I'm sorry if the interpretation is wrong. Since I get data from a database, I personally imagined a machine that searches in a library or a book search machine in a manga cafe. Then I felt that I could understand it, so I posted it ^ ^
Recommended Posts