Read more

Rails: Overwriting default accessors

Dominik Schöler
April 08, 2013Software engineer at makandra GmbH

All columns of a model's database table are automagically available through accessors on the Active Record object.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

When you need to specialize this behavior, you may override the default accessors (using the same name as the attribute) and simply call the original implementation with a modified value. Example:

class Poet < ApplicationRecord

  def name=(value)
    super(value.strip)
  end

end

Note that you can also avoid the original setter and directly read/write from/to the instance's attribute storage. However this is discouraged since you may skip other behavior from other overrides. If you are absolutely sure that you must do this, you can use read_attribute(attr_name) and write_attribute(attr_name, value). Example:

class Poet < ActiveRecord::Base

  def name=(name)
    write_attribute(:name, name.strip)
  end
  
end

See also

Posted by Dominik Schöler to makandra dev (2013-04-08 16:32)