Forum: Ruby on Rails active record logical cols

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.
915c75d80fe715ffe9772edd9c6a83d7?d=identicon&s=25 bramu.ss@gmail.com (Guest)
on 2009-03-18 05:56
(Received via mailing list)
HI,

   I am new to Rails started project couple of weeks back. Here is my
requirement please let me know the solution.

    When I do find on my active record class it returns all the
columns in my database table. I want to add one or two more cols to
the return record.

Like Student.find returns dob and name I want to add age to it some
thing like that. Columns that are not exist in the database table but
I want to add to the return record. How can I do this??

   Please reply asap I am totally struck on this.

Thanks,
Ramu.
280b78a61a968391b7e07e912be102a8?d=identicon&s=25 Robert Walker (robert4723)
on 2009-03-18 07:07
bramu.ss@gmail.com wrote:
> Like Student.find returns dob and name I want to add age to it some
> thing like that. Columns that are not exist in the database table but
> I want to add to the return record. How can I do this??

Age would just be a method on the Student model calculated from DOB:

class Student < ActiveRecord::Base

def age
  age = x # I'll assume you can figure out how to calculate age from DOB
end

Getting access to the existing attributes like date_of_birth is a simple
as:

self.date_of_birth # self in this case means the current instances of
the Student class since this is an instance method.

Remember that Ruby will return the value of the last line of the method
automatically so you don't have to include the return.
This topic is locked and can not be replied to.