2

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?

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
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.
4

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 %>

Comments

2

Try using send (see Ruby documentation).

1 Comment

No problem. Yes, Ruby is amazing! :)

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.