在ActiveRecord模型中定义临时属性

时间:2015-07-21 11:50:16

标签: ruby-on-rails rails-activerecord

我想在ActiveRecord模型中保存临时属性。

class Order < ActiveRecord::Base
  attr_accessor :order_total

  def order_total
    self[:order_total] = self.sale_sum + self.freight_charges
  end
end

order = Order.find(1)
order.order_total

我的问题是:如何在ActiveRecord模型中定义虚拟(又名临时)属性?

1 个答案:

答案 0 :(得分:1)

class Order < ActiveRecord::Base

  def order_total
    sale_sum + freight_charges
  end

end

order = Order.find(1)
order.order_total # will eq to sale_sum + freight_charges