Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a Model, how to loop through all properties?

I want to loop through all the properties of my 'user' model, how can I do this?

like image 345
Blankman Avatar asked Oct 26 '10 11:10

Blankman


1 Answers

If you have an instance of your model then user.attributes is a Hash of the model's attributes and their values so, for example, you can do something like:

user.attributes.each_pair do |name, value|   puts "#{name} = #{value}" end 

If you don't have a specific instance then the class has methods that return information about the fields in the database e.g. User.columns and User.content_columns. e.g.

User.columns.each do |column|   puts column.name end 
like image 141
mikej Avatar answered Sep 20 '22 13:09

mikej