Conditional statement in Rails

I am trying to get code to display based on a condition. I have a boolean field in a table called show_weekly. I am trying to do the following: if column == 1, then display the first row, the other to display the second line of code. for some reason it only shows the 2nd line.

<% if @listing.show_weekly == 1 %>

<%= number_to_currency(@listing.price/4, :unit => "&pound;") %> / week

<% else %>

<%= number_to_currency(@listing.price, :unit => "&pound;") %> / month
<% end %>

any help is appreciated. thank

+3
source share
5 answers

you need to check if it is equal true, not1

+2
source

The value of the boolean column will be either falseeither truein ruby, not 0or 1. So you should do:

<% if @listing.show_weekly %>

instead <% if @listing.show_weekly == 1 %>

+7
source

def print_price

   @p =  this.show_weekly? ? this.price / 4 : this.price 
   number_to_currency (@p, :unit => "&pound;")

end
+3

1 0, true false . .

show_weekly? , , -, .

, :

<% if @listing.show_weekly? %>
   ...
<% else %>
   ...
<% endif %>

. , , :

# 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)

Ruby, nil false , false, , , , nil. , true, false nil, , .

+2

If it @listing.show_weeklycontains a boolean, just check true:

<% if @listing.show_weekly %>

.....

<% else %>

....

<% end %>

Note that you do not even need a " == true". This is because the IF statement only looks at whether there is a value truereturned from any expression after it. If it @listing.show_weeklycontains a value true, then the entire IF statement sees that everything you provided to it.

0
source

Source: https://habr.com/ru/post/1796342/


All Articles