我有一个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>
答案 0 :(得分:1)
您可以在计算中使用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回调中使缓存失效。