开发者

How to loop through ActiveRecord values in Rails?

I have the following columns in my table:

value1 value2 value3 value4 value5

I want to be able to loop through them like 开发者_StackOverflowthis:

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


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.


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


Try using send (see Ruby documentation).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜