在条件语句中使用整数模型属性时遇到问题

时间:2014-02-01 23:36:54

标签: ruby-on-rails ruby ruby-on-rails-4

我在发布之后我刚刚解决了自己的问题:答案是只取走current_user.bedrooms整数的引号。有人能告诉我这是因为数字是整数而不是字符串吗?感觉很好解决这个问题,但想知道原因。

我正在尝试编写一些条件来将当前用户的卧室数转换为服务价格。

以下是相关代码:

<p>Price:</p><% if current_user.bedrooms == "1" %>
<%= "$100" %> 
<% elsif current_user.bedrooms == "2" %>
<%= "$120" %> 
<% elsif current_user.bedrooms == "3" %>
<%= "$140" %>  
<% elsif current_user.bedrooms == "4" %>
<%= "$160" %> 
<% elsif current_user.bedrooms == "5" %>
<%= "$190" %> 
<% else %>
<%= "$260" %>
<% end %> 

以下是用户在注册时选择该值的方式:

<%= f.label :select_home_size %> 
<%= f.select(:bedrooms, options_for_select([['Studio or 1 bedroom', 1], ['2 bedrooms', 2], ['3 bedrooms', 3], ['4 bedrooms', 4], ['5 bedrooms', 5]])) %>

我知道为current_user.bedrooms属性存储了一些内容,因为以下代码成功打印了用户以整数形式存在多少个卧室(例如3个卧室的“3”):

<p><strong>Number of bedrooms:</strong> <%= current_user.bedrooms %></p>

对于有3间卧室的用户,打印出“3”。对我做错了什么感到困惑。我是编程和rails的新手,所以它可能很简单我做错了。它只打印出“$ 260”的else语句,如果我把else语句带走,它什么都不打印。

1 个答案:

答案 0 :(得分:0)

我认为你的问题是你正在比较一个整数(current_user.bedrooms)和一个字符串,这就是为什么它总是转到else语句。你应该比较整数:

<% if current_user.bedrooms == 1 %>
  $100
<% elsif current_user.bedrooms == 2 %>
  $120
<% elsif current_user.bedrooms == 3 %>
  $140
<% elsif current_user.bedrooms == 4 %>
  $160
<% elsif current_user.bedrooms == 5 %>
  $190
<% else %>
  $260
<% end %>

你也可以稍微重构你的代码并将其移动到帮助器,例如:

module ServiceHelper
  def price_for_bedrooms(number_of_bedrooms)
    case number_of_bedrooms
    when 1 then "$100"
    when 2 then "$120"
    when 3 then "$140"
    when 4 then "$160"
    when 5 then "$190"
    else then "$260"
  end
end

 #In your view:
 <p>Price: <%= price_for_bedrooms(current_user.bedrooms) %></p>