Forum: Ruby How to cycle through an instance

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.
460ead051b49c0b2a8e45e46252d4bda?d=identicon&s=25 Tom Ha (tom)
on 2008-12-16 21:47
Hi there,

I'm sorry for this noob question (but at least it must be a quick one
for you guys):

I have an instance of an object in my database and need to get out every
element of it, like this:

Example: model = student
========================

firstname = Fred
lastname = Williams
streetname = NULL
city = NULL
date of birth = 12.12.1934
...
(until there is no more column name left for this model)

How do I correctly/efficiently cycle through this one?

Thank you very much for your help!
Tom
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2008-12-16 22:30
Tom Ha wrote:
> I have an instance of an object in my database and need to get out every
> element of it, like this:
>
> Example: model = student
> ========================
>
> firstname = Fred
> lastname = Williams
> streetname = NULL
> city = NULL
> date of birth = 12.12.1934
> ...
> (until there is no more column name left for this model)
>
> How do I correctly/efficiently cycle through this one?

Depends on what ORM you are using.

If it's ActiveRecord, try obj.attributes

(ActiveRecord questions probably best asked on the Rails mailing list
though)
460ead051b49c0b2a8e45e46252d4bda?d=identicon&s=25 Tom Ha (tom)
on 2008-12-16 22:36
Thanks a lot !
04952a6ee948f345e9c3727850d09a1b?d=identicon&s=25 Dejan Dimic (Guest)
on 2008-12-16 23:00
(Received via mailing list)
Have you try something like this:

@student = Student.find(params[:id])

@student.attribute_names.each do |attr_name|
  puts "#{attr_name} => #{@student.attribute[attr_name]}\n"
end

or

puts @student.attribute_names.map { |attr_name| "#{attr_name} => #
{@student.attribute[attr_name]}"}.join("\n")
460ead051b49c0b2a8e45e46252d4bda?d=identicon&s=25 Tom Ha (tom)
on 2008-12-17 10:27
Cool, thanks a bunch!
This topic is locked and can not be replied to.