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
Iterate over some_model_instance.attributes ?
Sent from my iPhone
On 16 Dec 2008, at 21:17, Tom Ha [email protected]
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…? 
On Tue, Dec 16, 2008 at 10:17 PM, Tom Ha
[email protected] 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
Gabriel L. [email protected]
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
[email protected]
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