2014-01-30 40 views
2

現在用戶可以通過表單將項目提交給站點。它收集的信息是買入價格,賣出價格和數量。從那裏,我計算出的利潤是這樣的:如何處理利潤?

<td><%= number_with_delimiter(((item.soldfor - item.boughtfor) * item.quantity)) %></td> 

我想接下來做的是顯示所有用戶已張貼在一定時間內像這樣的項目的利潤:

所有時間:1,000,000 |今天:102,111 |本週:200,111

問題是,利潤只是一個計算,我不能在任何其他地方調用它。我怎樣才能以一種能夠讓我這樣做的方式組織利潤計算?

回答

2

你應該寫上Item模型的方法返回利潤:

class Item < ActiveRecord::Base 
    ... 
    def profit 
    (soldfor.to_f - boughtfor.to_f) * quantity.to_f ## or use .to_i if you prefer integers 
    end 
    ... 
end 

然後在您看來,您可以撥打:

<td><%= number_with_delimiter(item.profit) %></td> 

或者,如果你想獲得的一切利潤總額在@items集合:

@items.sum(&:profit) 

所以你的情況,你可能會做這樣的事情在控制器:

@all_time_items = Item.where(<conditions for all_time>) 
@this_week_items = @all_time_items.where(<conditions for this_week>) 
@today_items  = @this_week_items.where(<conditions for today>) 

然後在你看來:

All time: <%= @all_time_items.sum(&:profit) %> | Today: <%= @today_items.sum(&:profit) %> | This week: <%= @this_week_items.sum(&:profit) %> 
1

你想動態調用方法嗎? 然後萊特輔助方法

def number_with_delimite(soldfor,boughtfor,quantity) 
    (soldfor - boughtfor) * quantity) 
end 

,在這裏你可以調用方法日期和時間的條件

number_with_delimite(item.soldfor.item.boughtfor,item.quantity)