Conditional statement in Rails
I'm trying to get some code to display based on a condition. I have a boolean field in a table called "show_weekly". What I'm attempting is: If the column == 1 then display the first line else display the 2nd 开发者_运维问答line of code. for some reason it's only showing the 2nd line.
<% if @listing.show_weekly == 1 %>
<%= number_to_currency(@listing.price/4, :unit => "£") %> / week
<% else %>
<%= number_to_currency(@listing.price, :unit => "£") %> / month
<% end %>
any help is greatly appreciated. thanks
The value of a boolean column will either be false
or true
in ruby, not 0
or 1
. So you should do:
<% if @listing.show_weekly %>
instead of <% if @listing.show_weekly == 1 %>
I'd suggest adding a method to your model
def print_price
@p = this.show_weekly? ? this.price / 4 : this.price
number_to_currency (@p, :unit => "£")
end
you need to check if it equals true
, not 1
A boolean value is stored as a 1 or a 0, but it is always interpreted as true
or false
before being returned from the model. This is a source of a lot of confusion.
Using the accessor method show_weekly?
can help because a question-mark in a method name usually indicates it will return a boolean value, or something that can be evaluated as boolean.
It will be a lot more readable if you have:
<% if @listing.show_weekly? %>
...
<% else %>
...
<% endif %>
Wherever possible, avoid comparing to specific hard-coded values. For instance, the following is redundant and yet I see it all the time:
# Example: Comparison to nil
if (@something == nil)
# Should be: Checking if initialized
if (@something)
# Example: Comparison to true
if (@something == true)
# Should be: Testing directly
if (@something)
As there are only two values that evaluate as false in Ruby, nil
and false
, it is generally the case that anything that is not true is nil. Occasionally you will have boolean columns that can be true
, false
or nil
if it is not defined, but this is unusual and can trip up people.
If @listing.show_weekly
contains a boolean value, just test for true :
<% if @listing.show_weekly %>
.....
<% else %>
....
<% end %>
Notice you don't even need the "== true
". This is because the IF statement only looks to see if there's a true
value returned from whatever expression follows it. If @listing.show_weekly
contains a value of true
then that's all the IF statement sees if that's all you provide it.
精彩评论