Skip to content


Intercepting ActiveRecord Attributes

So, you wrote a Rails application to track Marathon events. In a sudden change of heart, you pick up your company and move it from the United States to Germany. Why rewrite your app to handle metric distances? Rails provides a solution: write_attribute and read_attribute. For more information, you can refer to the official documentation.

1
2
3
4
5
6
7
8
9
class Marathon < ActiveRecord::Base
  def distance=(meters)
    write_attribute(:distance, meters * 1609.344)
  end

  def distance
    read_attribute(:distance) / 0.000621371192
  end
end

Posted in Uncategorized.