I often (very often) see code like this in the conditions:
<% catalog.each do |article| %>
<% if article.image.nil? %>
...
or (e.g. seen there)
<% catalog.each do |article| %>
<% if article.image.exists? %>
...
However we all know that nil interprets like false in the conditions. ActiveRecord query returns nil if nothing found.
Why not simply write:
<% unless article.image %>
(unless there is article do something)
instead of
<% if article.image.nil? %>
(if there is nothing at article.image do something)
and
<% if article.image %> instead of <% if article.image.exists? %>
I usually write the code without nil? and exists?. What am I missing? Is there any pitfalls?
nil?andexists?are very different.exists?is arailsquery method and can have additional conditions passed to it similar towherequery conditions. Also the query created is very different as wellexists?will generate a query likeSELECT 1 FROM table_name WHERE conditionsrather thanSELECT * FROM table_name WHERE conditionsthis can be far more efficient when the record actually exists because it does not actually create anActiveRecordobject but rather just returnstrueorfalse.