Rails: Overwriting default accessors

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

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

Dominik Schöler About 11 years ago