Forum: Ruby on Rails Shared Columns in an STI

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jim Schmidt (Guest)
on 2006-03-26 16:48
(Received via mailing list)
I have a an STI table which acts_as_tree, that has a large number of
classes/types. My common fields are:

id
parent_id
name
description

with 4 more text fields, I could cover most of my classes if I could
redefine the name of the field like this.

text1 AS address1
text2 AS address2
text3 AS zipcode

For one class and

text 1 AS model_number
text2 AS vendor


Is there a construct that will allow me to do this?

Thanks
Gregory S. (Guest)
on 2006-03-26 20:44
(Received via mailing list)
On Sun, Mar 26, 2006 at 07:48:33AM -0500, Jim Schmidt wrote:
} I have a an STI table which acts_as_tree, that has a large number of
} classes/types. My common fields are:
}
} id
} parent_id
} name
} description
}
} with 4 more text fields, I could cover most of my classes if I could
} redefine the name of the field like this.
}
} text1 AS address1
} text2 AS address2
} text3 AS zipcode
}
} For one class and
}
} text 1 AS model_number
} text2 AS vendor
}
}
} Is there a construct that will allow me to do this?

I just wrote something to do that for similar reasons:

class Super < ActiveRecord::Base

  def self.alias_field(old_field, new_field)
    define_method(new_field) { self.send(old_field) }
    define_method("#{new_field}=") { |arg| self.send("#{old_field}=",
arg) }
    define_method("#{new_field}?") { self.send("#{old_field}?") }
  end

end

class Sub < Super
  alias_field :text1, :address1
  alias_field :text2, :address2
  alias_field :text3, :zipcode
end

Now I can do all of the following:

fail "Where's the address?" unless foo.address1?
foo.address1 = '1600 Pennsylvania Ave.'
addr = foo.address1

...and it will use text1?, text1=, and text1, respectively.

} Thanks
--Greg
Jim Schmidt (Guest)
on 2006-03-27 02:08
(Received via mailing list)
Thanks, that is exactly what I need.
This topic is locked and can not be replied to.