ActiveRecord's attribute_in_database method
Wanted to share a method that I learned about today.
ActiveRecord has a handy utility for checking the value of an attribute in the database. These methods are actually on the Dirty module, and as such, are intended to be used when checking during validations or callbacks before saving.
These particular methods will read from the database (as their name implies), instead of using the value currently in memory.
There's 2 different methods to be aware of that you can use like below -
class Invoice < ActiveRecord::Base
validates :amount, presence: true
end
invoice = Invoice.last
invoice.amount
=> 10.0
invoice.amount = 80.0
invoice.attribute_in_database("amount")
=> 10.0
invoice.amount_in_database
=> 10.0
ActiveRecord::AttributeMethods::Dirty Docs
Tweet