stream
stream

Reputation: 379

Define a temporary attribute in an ActiveRecord model

I want to save a temporary attribute in an ActiveRecord model.

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

My question is: How can I define a virtual (aka temporary) attribute in an ActiveRecord model?

Upvotes: 0

Views: 637

Answers (1)

Nermin
Nermin

Reputation: 6100

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

Upvotes: 1

Related Questions