我有一个item
模型,需要计算总利润减去任何费用。我目前正在模型中执行此操作。但是,我希望仅在将布尔值更新为已售出后才能运行该计算。我已经在模型中尝试了if语句,但是没有用。
item.rb
class Item < ActiveRecord::Base
def profit_calc
sold_for - bought_for - fees - shipping rescue 0
end
def self.purchase_total
sum(:bought_for)
end
def self.fee_total
sum(:fees)
end
def self.shipping_total
sum(:shipping)
end
def self.sales_total
sum(:sold_for)
end
def self.profit_total
sum(:sold_for) - sum(:bought_for) - sum(:fees) - sum(:shipping)
end
scope :visible, -> { where(sold: false) }
scope :sold, -> { where(sold: true) }
end
schema.rb
create_table "items", force: :cascade do |t|
t.string "description"
t.float "bought_for"
t.float "sold_for"
t.float "fees"
t.float "shipping"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "sold", default: false
end
statistics.html.erb
<td><%= number_to_currency(@items.profit_total) %></td>
您可以sold
在计算中使用范围:
def self.profit_total
sold.sum(:sold_for) - sold.sum(:bought_for) - sold.sum(:fees) - sold.sum(:shipping)
end
但是每次调用Item.profit_total
它都会执行所有查询。如果您经常需要,可能要缓存计算,如果已售出,则在after_save回调中使缓存过期。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句