开发者

Rails: How to name and create unique divs within a loop?

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 whenev开发者_如何学Cer 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?


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>

......


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

Sorry for earlier omission. This should work.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜