views:

432

answers:

3

Hey! I iterate through a hash with @lists.each do |list|. I create a div in every cycle that must have an id. I would have created a count variable in PHP to get a definite id. What is the best way to do that in a Rails view? Thank you!

+5  A: 

Assuming these are ActiveRecord models (ie. from a database), you could just use the dom_id helper, like so:

<% @lists.each do |list| %>
  <div id="<%= dom_id(list) %>">
    ... rest of list ...
  </div>
<% end %>

That way each div will get an ID like list_49, with the number corresponding to the ID in the database.

Luke
Thanks Luke, I didn't know the dom_id-helper before. :)
Javier
+2  A: 

An alternative would be to use the div_for helper:

<% @lists.each do |list| %>
  <% div_for(list) do %>
    ... content in div ...
  <% end %>
<% end %>

That will add the same format of id as Luke's suggestion. Be aware though that it would also add a class attribute of list. You can add additional classes by passing in :class => 'my-class'.

Matt
A: 

Why don't you just take the id of the list? Or must the id be any kind of "globally unique"?

Update: I think you should go with luke's answer.

Javier