2015-08-14 24 views
0

我有一個簡單的軌道應用程序,我試圖寫一個視圖助手,執行以下操作。在視圖助手中的條件CSS的軌道

比較兩個值。如果current_month的金額大於預測金額,則將文本設爲綠色。如果current_month的金額低於預測金額,則將文本設爲紅色。

我寫出了這個簡單的助手,以將文本追加到rails方法的輸出,但我不確定如何注入CSS /樣式到此。

def target_hit(forecast, current) 
    (if current.amount > forecast.amount 
    number_to_currency(current.amount.to_s) + " Yay" 
    elsif current.amount < forecast.amount 
    number_to_currency(current.amount.to_s) + " No dice" 
    end).html_safe 
end 

我非常精通後端,但當涉及到前端的東西,我絆倒了很多。任何幫助將不勝感激。

例如圖碼

<p class='total'>Current: <%= target_hit(@forecast, @current) %></p> 
+0

您還可以從一個類的輔助方法。或者在你的target_hit方法中,你可以使用content_tag來定義類。我需要看到你的觀點來提供一個例子。 – margo

+0

@margo我提供了關於我如何稱此方法的觀點摘錄。 – nulltek

回答

1

軌道幫手content_tag http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag,是有用的,意味着你不必使用html_safe。我嘗試將視圖中的所有邏輯移至助手,以使視圖易於閱讀,例如

def target_hit(current_amt, forecast_amt) 
    content_tag(:p, "#{number_to_currency(current_amt.to_s)} target_content(current_amt, forecast_amt)", class: "total #{target_class(current_amt, forecast_amt)}") 
end 

def target_content(current_amt, forecast_amt) 
    forecast_reached?(current_amt, forecast_amt) ? "Yay" : "No dice" 
end 

def target_class(current_amt, forecast_amt) 
    forecast_reached?(current_amt, forecast_amt) ? "green" : "red" 
end 

def forecast_reached?(current_amt, forecast_amt) 
    current_amt >= forecast_amt 
end 

在視圖中,你只需要調用輔助方法

<%= target_hit(@current.amount, @forecast.amount) %> 
+0

這比我自己想出的要簡單得多。我非常喜歡這個答案。將盡快upvote :) – nulltek