2017-02-14 37 views
0

我有一个Rails 3.2视图,正在创建一个列表。如果costestimate.costcat.position等于1(列表中只有一个),我想保存一个变量用于列表的其余部分。导轨 - 保持一个变量,当你通过。每个

 <% @costproject.costestimates.each do |costestimate| %> 
     <% if costestimate.costcat.position = 1 %> 
      <% $constructioncost = costestimate.amount %> 
     <% end %> 
     <% if costestimate.costcat.typical != nil %> 
      <% costtypical = costestimate.costcat.typical * $constructioncost %> 
     <% end %> 
     <td><%= costtypical %></td> 
     <td><%= costestimate.notes %></td> 

但是,在每个周期后,$ constructioncost变为零。我认为$会使它成为一个全局变量。

回答

0

它不工作,因为你使用赋值运算符,而不是比较if costestimate.costcat.position = 1应该if costestimate.costcat.position == 1

我建议不要使用全局变量,并在视图中具有所有的逻辑。在你的情况下,如果你在costproject中每costestimate有一个乘数,那么将它保存在costproject以内可能是有意义的。根据您的应用程序的结构,可以在costestimate类,帮助程序,服务对象或其他地方完成每个costestimate的计算costtypical。只是不在视图中。

至少,让您的VAR循环外,没有全局变量:

<% constructioncost = @costproject.costestimates.find{|c| c.costcat.position == 1}.amount %> 
<% @costproject.costestimates.each do |costestimate| %> 
    <% if costestimate.costcat.typical != nil %> 
     <% costtypical = costestimate.costcat.typical * constructioncost %> 
    <% end %> 
    <td><%= costtypical %></td> 
    <td><%= costestimate.notes %></td> 
+0

移动它的外循环的工作 - 感谢 – Reddirt

0

有可能是在你的代码导致错误怪异的结果:

<% if costestimate.costcat.position = 1 %> 

应该

<% if costestimate.costcat.position == 1 %> 
相关问题