Search code examples
ruby-on-railsrubyrails-activerecord

Ruby / Rails expression. What is self[:reason] in an ActiveRecord class?


I have found the following expression in a very old piece of code:

def reason
  self[:reason].try(:to_sym)
end

This is a method in an ordinary model class (ultimately) inheriting from ApplicationRecord, nothing fancy.

Can anybody explain to me what self[:reason] might be?


Solution

  • ActiveRecord::AttributeMethods#[] returns the value of the attribute after it has been typecast

    Probably same effect but more readable:

    def reason
      super&.to_sym
    end