require 'active_record' ActiveRecord::Base.class_eval do def self.object_id_attr(symbol, klass) module_eval %{ def #{symbol} if @#{symbol}.nil? or (@old_#{symbol}_id != #{symbol}_id) @old_#{symbol}_id = #{symbol}_id klass = #{klass}.descendants.find { |d| d.#{symbol}_name == #{symbol}_id } klass ||= #{klass} @#{symbol} = klass.new else @#{symbol} end end } end end