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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)