How to iterate through an instance


#1

Hi there,

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)

If it was an array, I’d use: .each { … }

How do I correctly/efficiently cycle through this one?

Thank you very much for your help!
Tom


#2

Iterate over some_model_instance.attributes ?

Sent from my iPhone

On 16 Dec 2008, at 21:17, Tom Ha removed_email_address@domain.invalid


#3

Yeah! I guess that will then be something like…

some_model_instance.attributes.each { … }

Going to try that…

Thanks, Fred!

(do you ever stop working…? :wink:


#4

On Tue, Dec 16, 2008 at 10:17 PM, Tom Ha
removed_email_address@domain.invalid wrote:

lastname = Williams
streetname = NULL
city = NULL
date of birth = 12.12.1934

(until there is no more column name left for this model)

If it was an array, I’d use: .each { … }

How do I correctly/efficiently cycle through this one?

I don’t know if its efficient, or right, but
ActiveRecode::Base#attributes [1]
seems to do the job

If you already know the fields, you can also do something like that :

[ :firstname, :lastname, … ].each do |attr|
val = model.send attr
end

Hope it will help

[1] : http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002047

Gabriel L. removed_email_address@domain.invalid


#5

Thanks a bunch, guys!


#6

On Dec 16, 2008, at 4:40 PM, Frederick C. wrote:

I have an instance of an object in my database and need to get out
date of birth = 12.12.1934

(until there is no more column name left for this model)

If it was an array, I’d use: .each { … }

How do I correctly/efficiently cycle through this one?

Thank you very much for your help!
Tom

Or Student.column_names.each {|column| puts “#{column} =
#{student.send(column)}” }

You might display something like column.humanize.downcase if you need
‘date of birth’ with the spaces.

-Rob

Rob B. http://agileconsultingllc.com
removed_email_address@domain.invalid


#7

Tom,

You may try the inspect() way:

inspect()

Returns a string like ‘Post id:integer, title:string, body:text‘

File vendor/rails/activerecord/lib/active_record/base.rb, line 1348

1348: def inspect
1349: if self == Base
1350: super
1351: elsif abstract_class?
1352: “#{super}(abstract)”
1353: elsif table_exists?
1354: attr_list = columns.map { |c| “#{c.name}: #{c.type}” }

  • ', ’
    1355: “#{super}(#{attr_list})”
    1356: else
    1357: “#{super}(Table doesn’t exist)”
    1358: end
    1359: end

Cheers, Sazima