In the Rails view, there was a scene to write a process like "display if there is an image". There are several methods for checking the existence, including those for Ruby and those for Rails. After a little research, I selected the method "OK, let's go with this!" And submitted it for review, but it was completely crushed, so I will keep it as a memorandum so that I will not make a mistake in the future.
macOS Catalina Version 10.15.5 Ruby: 2.6.5 Ruby on Rails: 6.0.3
There have been similar articles in the past, and most of them are actually "ruby's authenticity judgment method (nil? / Empty? / Blank? / Present?) Turned out to be interesting //qiita.com/go_d_eye_0505/items/541110cb9821734b0623) ”. On top of that, the reasons for posting this time are as follows.
--The any? Method was not mentioned in the above post, but I also wanted to confirm the behavior of any? (Because I faced the problem of array entanglement this time).
--In the summary table of the above post,
-"** A method to ask if there is ** (present? Etc., returns true if there is something)"
-"** Not ** or not" Method to listen to (empty? Etc., returns true if there is nothing) "
was written side by side, but a table with the direction of the condition aligned, such as" returns 〇〇 if there is something " I wanted (a table where present? And not empty? Can be compared)
* Of course, the merit of the above table is that it is easy to understand that present? And blank? Are in a back relationship.
In addition, blank? Is excluded (because the definition of present? Is! Blank?).
Use rails console.
test =XXX ← Substitute variously here test.any? !test.empty? test.present? !test.nil?
Array(The element is nil)
From this result, I have emphasized the points that I should be careful about in the future in capital letters in the table, but I will describe them again below.
! Empty?and returns true, and in
present?it is regarded as empty and returns false
blank?) Has a wide range of empty judgments.
! Nil?, It returns false, but if you ask the array made of
[nil], it returns true.
In Rails, there is also a method called ʻexists?
. This seems to be used to check if the database has data with specific conditions, and it was a method defined in ʻActiveRecord :: Base. I didn't know about it and initially included it in the investigation, but all returned
This is Qiita's first post. I think the content is simple and natural, but it was a good opportunity to deepen understanding through the process of examining and organizing for output. I would like to regularly post articles that will be useful to me (≒ others) in the future.