2014-01-30 38 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)