views:

25

answers:

3

I have the following columns in my table:

value1 value2 value3 value4 value5

I want to be able to loop through them like this:

<% for i in 1..5 %>
  <div><%= user."value#{i}"</div>
<% end %>

Of course this code doesn't work, so how can I get the value from an ActiveRecord object with a string?

+2  A: 

Try using send (see Ruby documentation).

Kevin Sylvestre
Thanks, exactly what I need! Ruby is amazing.
Alex
No problem. Yes, Ruby is amazing! :)
Kevin Sylvestre
+3  A: 

You can use the send method to send a method name to any object as a string. The example below is what you're looking for.

<% for i in 1..5 %>
  <div><%= user.send("value#{i}") %></div>
<% end %>
Mike Trpcic
+2  A: 

Wow, unless you really have a bad naming convention for your attributes, the send method is only going to get you halfway there. Are your attribute names really numbered sequentially?

Here's how to loop through your attributes regardless of their names:

<% user.attributes.each do |name, value| %>
  <div>
    <%= name %>: <%= value %>
  </div>
<% end %>

I hope this helps, let me know if you have any questions.

Jaime Bellmyer
The problem with this is that it will do all attributes. It's entirely possible that his Rails application is interacting with some horribly formatted/named legacy database, and there are 5 fields named "contact1", "contact2" and so on.
Mike Trpcic
This will certainly loop through all attributes, as advertised. If you want to weed some out, you can easily do that with the select method. I just didn't want him feeling like he has to name fields that way to be able to loop through them.
Jaime Bellmyer
Like Mike said, there's some horrible stuff in the database that literally looks like this: value1, value2, value3, value4, value5. So yes, they are numbered sequentially. Good point though.
Alex