2010-01-27 42 views
1

我是Ruby on Rails的新手,以及確保我在右腳上設置的內容。我想做一些簡單的「實時計算」,我不確定最好的方法。 如果我們使用食譜示例。新手 - 導軌視圖計算 - onchange?

每個食譜有很多成分。 每種成分都有描述,數量,成本和總數。

我想要做的是以下; 1)ingredient.total = ingredient.qty X ingredient.cost 2)recipe.grand_total = ingredients.sum(總數)

每當用戶改變ingredient.qty或ingredient.cost值我想更新總數。

什麼,我不知道是如何或在哪裏做:(

任何幫助將是提前偉大:)

感謝, 尼爾

回答

0

我認爲你需要通過在上面提到的兩個字段上使用onChange或者observe_field來使用javascript來做到這一點。

當其中一個更新時,JavaScript會調用您的代碼位來執行計算。

+0

嘿, 感謝您的信息。我也這麼認爲,但我只能找到一些實例,以便在更新時實際發佈表單。我希望計算保留在客戶端(或者至少不更新數據庫),直到用戶保存表單。從而給他們一個取消的機會。你能爲我指出正確的方向嗎?再次感謝尼爾 – Neil 2010-01-27 14:24:37

0

一直在亂搞,到目前爲止都想出了這個解釋從各個地方拉到一起,所以想到我會分享。

<tr class="recipe_item"> 
    <td><%= f.text_field :ingredient %></td> 
    <td><%= f.text_field :quantity, :class => "quantity", :onblur => "this.up('.recipe_item').down('.total').value = (parseInt(this.value) * parseInt(this.up('.recipe_item').down('.cost').value)) ;" %></td> 
    <td><%= f.text_field :cost, :class => "cost", :onblur => "this.up('.recipe_item').down('.total').value = parseInt(this.up('.recipe_item').down('.quantity').value) * (parseInt(this.value)) ;" %></td> 
    <td><%= f.text_field :total, :class => "total", :readonly => true %></td> 
</tr> 

不知道這是多高效,但似乎至少在第一步工作。接下來的事情是找到一種方法來將所有的食譜項目總和。任何人有任何意見或想法? 謝謝 尼爾