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.
Tom H. (Guest)
on 2008-12-16 22: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
Brian C. (Guest)
on 2008-12-16 23: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)
Tom H. (Guest)
on 2008-12-16 23:36
Thanks a lot !
Dejan D. (Guest)
on 2008-12-17 00: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")
Tom H. (Guest)
on 2008-12-17 11:27
Cool, thanks a bunch!
This topic is locked and can not be replied to.