【发布时间】:2020-06-29 08:01:43
【问题描述】:
<% 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 变量设置为 false
Parameters: { "for_sale"=>"false", "id"=>"3"}
这是将其设置为 false 的代码:
<%= form.select :for_sale, options_for_select({ "Yes" => true, "No" => false }
因此 else 语句应该运行。然而,这并没有反映在视图方面。我在这里错过了什么?
编辑 1
“for_sale”变量默认设置为true。
t.boolean "for_sale", default: true
但是,当我使用上面显示的 options_for_select 代码将其更改为 false 时,它仍然保持为 true。
有什么线索吗?
编辑 2
解决了! for_sale 变量未包含在 property_params 中
def property_params
params.require(:property).permit(:name, :address, :price, :rooms, :bathrooms, :parking_spaces,:details, :photo, :photo_cache, :for_sale)
end
【问题讨论】:
-
您是否尝试过打印
false的类型以确保您收到的是布尔值? -
使用
"false"将运行真实性检查,对于这种情况,只需作为字符串,它将采用您的 if 条件的真正“路径”。在这种情况下,请检查@property.for_sale?== 'false'(或 'true')。 -
@SebastianPalma 这行得通。谢谢!但是,我仍然无法理解为什么“false”是一个字符串,尽管代码清楚地生成了一个布尔值?
-
在 HTML 中并没有
true和false这样的东西,它只是文本。options_for_select正在创建类似<option value="true">Yes</option>, and itsvalue 的东西,在 Ruby 中将被解释为字符串。数字也可以这样说(例如value="1") -
因为在@SantiagoCepeda 之后,所有转换为参数的东西都变成了字符串。
标签: ruby-on-rails ruby-on-rails-5