views:

50

answers:

2

I have a view with a div that is looped many times. Each of the created divs need to have a unique ID so I can access them specifically (at the moment, all my divs have the same ID specified in html so whenever I try to access a specific div it just finds the first one).

This is the version that I currently have (multiple 'rowBox'es are not discernible).

<% @customers.each do |customer| %>
  <div id="customer" class="rowBox">
  ...
  </div>
<% end %>

I would like to be able to do something like:

<% @customers.each do |customer| %>
  <div id="box<%=customer.id%>">
  ...
  </div>
<% end %>

This doesn't seem to work. Any ideas on how to accomplish this?

A: 
<% @customers.each do |customer| %>
  <div id=<%= "box#{customer.id}" -%>>
  ...
  </div>
<% end %>

Sorry for earlier omission. This should work.

mark
+2  A: 

Rails has some handy helpers for exactly this.

<% @customers.each do |customer| %>
  <% div_for customer, :class => "rowBox" do %>
    ...
  <% end %>
<% end %>

This will produce e.g.:

<div id="customer_1" class="customer rowBox">
  ...
</div>

<div id="customer_2" class="customer rowBox">
  ...
</div>

...
Jordan
If they're new objects this won't work. You can also use `each_with_index do |c, i|` which will give you a loop counter.
jonnii
@jonnii - how would that work in the code?
sscirrus