3
      <% 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
5
  • 1
    have you tried to print the type of false to make sure that you receive it as boolean? Commented Jun 29, 2020 at 8:07
  • 2
    Using "false" would run a truthiness check, and for that case simply by being a string, it'll take the true "path" of your if condition. In that case, check just if @property.for_sale? == 'false' (or 'true'). Commented Jun 29, 2020 at 9:15
  • @SebastianPalma This worked. Thanks! I still cannot understand, however, why "false" is a string, although the code clearly generates a boolean? Commented Jun 29, 2020 at 9:46
  • 1
    In HTML there is no such thing really as true and false, it is all just text. options_for_select is creating something like this <option value="true">Yes</option>, and its value` will be interpreted in Ruby as a string. Similar can be said for numbers (eg. value="1") Commented Jun 29, 2020 at 9:58
  • 1
    Because everything that's converted to params becomes a string after all @SantiagoCepeda. Commented Jun 29, 2020 at 10:07

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

That would be your if statement. So <% if ActiveModel::Type::Boolean.new.cast(@property.for_sale) %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.