Overriding Rails ActiveRecord object getter/setter fields

Lets say you have a widget model in Ruby on Rails.  Your database table contains a field called “name”.  Let’s say you want to add something to this field in your model.  You need a specialized def in order to do this.. you need to use write_attribute and read_attribute methods.

Here is an example where I override the Rails ActiveRecord model attribute setter. This will append a test string onto the name:

class Widget < ActiveRecord::Base
  def name=(name)
    write_attribute(:name,"#{name} - test")
  end
end

You can also do this with the read_attribute method and it works the opposite way… instead of operating on the setter, you operate on the getter.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.