Rails: Overwriting default accessors

Updated . Posted . Visible to the public. Repeats.

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
Last edit
Michael Leimstädtner
Keywords
getter, setter
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2013-04-08 14:32)