Monday, October 16th, 2006...7:41 pm
Derived Columns in ActiveRecord
Jump to Comments
Sometimes it's useful to have a field in your ActiveRecord implentation that isn't actually selected in your query or present in your table. One way to acheive this is by simply adding a new accessor to your Model class.
Let's say we have a table named Customers that has a firstname and lastname column but we would like to also have a fullname column available to us when doing things like iterating through Customer objects in our view. One way is to add it directly to our Customers class ( app/model/customer.rb in your rails app).
class Customer <ActiveRecord::Base
def fullname
@fullname = self.firstname + ' ' + self.lastname
end
def fullname
@fullname = self.firstname + ' ' + self.lastname
end







1 Comment
October 16th, 2006 at 11:29 pm
You might check out the 'composed_of' macro/metatool that's in ActiveRecord. It can do a lot of this for you.