Rails - 发票应用程序

时间:2016-02-23 04:24:08

标签: ruby-on-rails

我正在Rails中构建一个Invoicing App,其中包含以下模型。

class Company < ActiveRecord::Base
  has_many :clients
  has_many :items

class Client < ActiveRecord::Base
  belongs_to :company

class Invoice < ActiveRecord::Base
  belongs_to :company
  belongs_to :client
  has_many :line_items
  has_many :items, through: :line_items
  accepts_nested_attributes_for :line_items

  after_initialize :set_total

  def set_total 
    total = 0 
    items.to_a.each do |item| 
      total += item.price * item.qty 
    end 
    self.total = total 
  end

class Item < ActiveRecord::Base
  belongs_to :company
  has_many :line_items
  has_many :invoices, through: :line_items

class LineItem < ActiveRecord::Base
  belongs_to :invoice
  belongs_to :item

目前我能够成功生成发票。每当我更改以生成的发票为参照的商品价格时,问题就是发票的总金额变化。

防止这种情况发生的最佳方法是什么?创建发票后,我不希望对其总数进行任何更改。

由于

2 个答案:

答案 0 :(得分:0)

在初始化新记录时以及从数据库中提取记录时都会调用

after_initialize

您可能希望使用before_create代替after_initialize,以便在创建前只设置一次,并且每次初始化记录时都不会更新。

您还可以按如下方式简化set_total方法:

def set_total
  self.total = items.inject(0) { |sum, item| sum + (item.price * item.qty) }
end

有关注入的详细信息,请参阅Enumerable#inject

答案 1 :(得分:0)

你可以使用new_record吗?方法,

&#13;
&#13;
  after_initialize :set_total

  def set_total 
    total = 0 
    items.to_a.each do |item| 
      total += item.price * item.qty 
    end 
    self.total = total if self.new_record?
  end
&#13;
&#13;
&#13;