I want to loop through all the properties of my 'user' model, how can I do this?
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
Article.columns.each do |column|
puts column.name
end
This iterates over all the column objects for the Article model.
@model.methods returns the names of all methods of the object.
@model.methods.grep(/=$/) will return you the names of all write methods, so you can guess that if you have a setter, then you also have a reader, so this may be a "property".
You may also inspect the attributes hash (@model.attributes) which is a Hash with all the columns defined in the database, and this may be the most reliable way, since the "methods" method may not include the attribute readers (and writers) generated dynamically. (It may depend on the version of RubyOnRails you are using).