Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override ActiveRecord attribute methods

Echoing Gareth's comments... your code will not work as written. It should be rewritten this way:

def name=(name)
  write_attribute(:name, name.capitalize)
end

def name
  read_attribute(:name).downcase  # No test for nil?
end

As an extension to Aaron Longwell's answer, you can also use a "hash notation" to access attributes that have overridden accessors and mutators:

def name=(name)
  self[:name] = name.capitalize
end

def name
  self[:name].downcase
end

There is some great information available on this topic at http://errtheblog.com/posts/18-accessor-missing.

The long and short of it is that ActiveRecord does correctly handle super calls for ActiveRecord attribute accessors.