现在,用户可以通过表单向网站提交项目。它收集的信息是买入价格、卖出价格和数量。从那里,我计算出这样的利润:
<td><%= number_with_delimiter(((item.soldfor - item.boughtfor) * item.quantity)) %></td>接下来我要做的是显示用户在特定时间框架内发布的所有项目的利润,如下所示:
全时: 1,000,000 -今天: 102,111 -本周: 200,111
问题是利润只是一种计算,我不能在其他地方调用它。我如何组织计算利润的方式,使我可以这样做?
发布于 2014-01-30 07:47:54
您应该在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) %>发布于 2014-01-30 07:41:14
要动态调用方法吗?然后wright介绍了helper方法
def number_with_delimite(soldfor,boughtfor,quantity)
(soldfor - boughtfor) * quantity)
end在这里,您可以调用具有日期和时间条件的方法。
number_with_delimite(item.soldfor.item.boughtfor,item.quantity)https://stackoverflow.com/questions/21447513
复制相似问题