2017-02-14 36 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 %>