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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)