Reputation: 6907
In my Rails 4 app, there is a Post model, with both a :copy
and a :short_copy
attribute.
In the Posts#Show view, I want to display the :short_copy
if it was defined by the user, and the :copy
otherwise.
So, I implemented the following code:
<% if @post.short_copy %>
<%= @post.short_copy %>
<% else %>
<%= @post.copy %>
<% end %>
Problem: when the :short_copy
is defined, it does show up, however, when it is not defined (and a :copy
is defined), the :copy
does not show up.
Is there something wrong with this code?
Upvotes: 1
Views: 120
Reputation: 191
I always use string.blank?
to check if nil or empty string. Use array.empty?
if field is array. So in your case, you can use blank?
<% unless @post.short_copy.blank? %>
<%= @post.short_copy %>
<% else %>
<%= @post.copy %>
<% end %>
Upvotes: 1
Reputation: 6649
I just run this snippet:
2.1.1 :002 > if("")
2.1.1 :003?> printf "yes"
2.1.1 :004?> else
2.1.1 :005 > printf "no"
2.1.1 :006?> end
(irb):6: warning: string literal in condition
yes => nil
So - if short_copy is empty string, it will evaluate to true. So try this:
2.1.1 :020 > unless("".empty?)
2.1.1 :021?> printf "yes"
2.1.1 :022?> else
2.1.1 :023 > printf "no"
2.1.1 :024?> end
no => nil
Upvotes: 1
Reputation: 32748
Use String#blank?
to check for a value - an empty string is still true
<% if [email protected]_copy.blank? %>
<%= @post.short_copy %>
<% else %>
<%= @post.copy %>
<% end %>
Upvotes: 3
Reputation: 1943
I would argue that there is nothing wrong with your code in essence, but you may be mislead by the value of @post.short_copy. Unless it is nil
or false
the <% if @post.short_copy %>
will be run. I would imagine that @post.short_copy = ''
, and is therefore displaying nothing in the view.
Upvotes: 2