现在用户可以通过表单向网站提交项目。它收集的信息是买入价、卖出价和数量。从那里,我计算利润如下:
<td><%= number_with_delimiter(((item.soldfor - item.boughtfor) * item.quantity)) %></td>
接下来我想做的是显示用户在特定时间范围内发布的所有项目的利润,如下所示:
All time: 1,000,000 | Today: 102,111 | This week: 200,111
问题是利润只是一种计算,我无法在其他地方调用它。我怎样才能以一种允许我这样做的方式组织利润的计算?
最佳答案
您应该在 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)
因此,在您的情况下,您可能会在 Controller 中执行类似的操作:
@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) %>
关于ruby-on-rails - 怎样做才能有利润?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21447513/