0

I have another question involving each loops. I have a view which displays a current classroom. It shows how many students are online atm, etc. Within a div located on the bottom right i have a table that lists all the available classrooms. The "name" of the classroom is a button which makes the page refresh with new parameters (:class_id) and then shows the "clicked" classroom.

My problem is identifying the proper ID for each row in the table within the each do loop.

I have this code in my view (Example)

<% @classrooms.each do |room| %>
<table>
  <tr>
     <td><%= room.id %></td>
     <td><button onclick= "class()"><%= room.class %></button></td>
  </tr>
</table>
<script>function class(){window.location = '<%= classroom_path(:class_id = room.id)%>'};</script>
<% end %>

Its redirecting with the new param, but the class_id is the same for all the entries (last one). Any help? This is probably fairly simple, not sure.

4

2 回答 2

1

I'm confused. Why not use a real link ?

<% @classrooms.each do |room| %>
  <%= link_to room.class, classroom_path(room) %>
<% end %>

If you don't want a link (which can be styled as a button with virtually any css framework; including bootstrap); you can always do :

<% @classrooms.each do |room| %>
  <%= button_to classroom_path(room), method: :get, value: room.class %>
<% end %>

if you want to do it via js / jquery, here you go:

<% @classrooms.each do |room| %>
  <%= tag :button, data: {url: classroom_path(room)}, class: 'js_button' ,value: room.class %>
<% end %>
<script type="text/javascript">
  $(document).on('click', '.js_button', function(){
    window.location = this.getAttribute("data-url");
  });
<script>

also, typo: classroom_path(:class_id = room.id)

于 2013-10-29T18:02:14.260 回答
0

Your syntax looks wrong. Try

<td><%= room.id %></td>

And also <%= room.class %>

If you want to output data in erb, you need <%= not just <%`

Also, you are redefining the class() function for each @classroom object, so any button click would call the same function each time. You aren't making a new function for each instance.

But, this could all be cleaned up much easier by just doing a simple link_to and using path helpers like <%= link_to room.class, class %>

于 2013-10-29T18:01:00.217 回答