Santiago Cepeda
Santiago Cepeda

Reputation: 31

Ruby on Rails if statement not working, although variable has a Boolean value

      <% if @property.for_sale? %>
    <%= @property.price > 0 ? number_to_currency(@property.price, precision: 0) : "For Sale" %>
  <% else %>
     <%= @property.price > 0 ? number_to_currency(@property.price, precision: 0) : "For Rent" %> / month
  <% end %>

for_sale variable is set to false

Parameters: { "for_sale"=>"false", "id"=>"3"}

This is the code that sets it to false:

<%= form.select :for_sale, options_for_select({ "Yes" => true, "No" => false }

Therefore the else statement should run. However, this is not reflected on the view side. What am I missing here?

edit 1

"for_sale" variable is set to true by default.

t.boolean "for_sale", default: true

However, when I change it to false with the options_for_select code shown above it still remains as true.

Any clue why?

edit 2

Solved it! for_sale variable was not included in property_params

def property_params
  params.require(:property).permit(:name, :address, :price, :rooms, :bathrooms, :parking_spaces,:details, :photo, :photo_cache, :for_sale)
end

Upvotes: 3

Views: 228

Answers (1)

NM Pennypacker
NM Pennypacker

Reputation: 6942

One way to handle the case of 'false' being a string OR a boolean value of false would be to typecast the value. Since you're using Rails you can do:

ActiveModel::Type::Boolean.new.cast(@property.for_sale)

This will ensure that both 'false' and false evaluate to false

Upvotes: 2

Related Questions