44

Is it possible to loop over an object's attributes in Rails? I have an object and rather than code up each attribute in the view, I want to output each of them in the view as there are quite a few.

I have an object called @work_profile which has many attributes, mainly boolean check box values.

Edit: I see I can use @work_profile.attributes. Any help on formatting the hash into something more user friendly would be great.

1 Answer 1

76

The ActiveRecord::Base.attributes() method returns a hash of all the attributes. You can use that to loop over all attributes.

@work_profile.attributes.each do |attr_name, attr_value|
  ...
end

In a view, this would give:

<% @work_profile.attributes.each do |attr_name, attr_value| %>
  <div class="work_profile_attribute">
    <%= attr_name %>: <%= attr_value %>
  </div>
<% end %>
Sign up to request clarification or add additional context in comments.

4 Comments

Great that's what I was looking for. How can format the output of the hash in the view?
I'm not entirely sure what you mean by the output of the hash but I added a code snippet that shows how you could loop over the attributes in a view. Just an example...
Is there a way to convert the attr_name to something more friendly? Ie: have_a_car: true to something more like Have a car: true
Try attr_name.humanize. This will convert a string such as "have_a_car" into "Have a car". Note that the String#humanize method is provided by Rails so this won't work outside of a Rails environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.