【问题标题】:Ruby on Rails if statement not working, although variable has a Boolean valueRuby on Rails if 语句不起作用,尽管变量具有布尔值
【发布时间】: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 正在创建类似 &lt;option value="true"&gt;Yes&lt;/option&gt;, and its value 的东西,在 Ruby 中将被解释为字符串。数字也可以这样说(例如value="1")
  • 因为在@SantiagoCepeda 之后,所有转换为参数的东西都变成了字符串。

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

处理'false' 是字符串或布尔值false 的一种方法是对值进行类型转换。由于您使用的是 Rails,您可以这样做:

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

这将确保'false' 和false 都评估为false

【讨论】:

  • 那将是您的 if 语句。所以&lt;% if ActiveModel::Type::Boolean.new.cast(@property.for_sale) %&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
相关资源
最近更新 更多