新手问题 请教一个关于如何在 ActiveRecord 中怎样自定义属性的问题

saxer · July 21, 2015 · Last by saxer replied at July 21, 2015 · 1552 hits
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
#=>ActiveModel::MissingAttributeError (can't write unknown attribute `order_total`):
class Order < ActiveRecord::Base
  def order_total
    sale_sum + freight_charges
  end
end

#1 楼 @rei 恩 这样也能计算出订单的总花费,但是有个问题,每次我调用 order.order_total 时,代码会重复执行sale_sum+freight_charges 请问下如果我想使用 order[:order_total] 应该怎样实现啊?我的目的是在 ActiveRecord 中保存一份临时数据,下次其他代码调用此变量时不会重复计算

class Order < ActiveRecord::Base
  def order_total
    @order_total ||= sale_sum + freight_charges
  end
end

但是要小心依赖的两个属性变了怎么办,我觉得加操作这么简单的运算不用缓存。

#3 楼 @rei 好的,谢谢

更新:attr_accessor 不需要。

You need to Sign in before reply, if you don't have an account, please Sign up first.