Today I Learned

hashrocket A Hashrocket project

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

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.