Search code examples
javascriptajaxruby-on-rails-4renderpartial

Rails Ajax Javascript render partial with collection shows nothing


In my index.html.erb file I have:

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Note</th>
      <th colspan="2"></th>
    </tr>
  </thead>

  <tbody id="avail-courses">
    <%= render partial: 'avail_course', collection: @courses %>
  </tbody>
</table>

Which basically render a partial _avail_course.html.erb.

I am trying to make this render through an ajax call, so I made my javascript file enroll.js.erb as:

$('#avail-courses').html("<%= escape_javascript render partial: 'avail_course', collection: @courses %>");

The ajax call is successfully made, but the render returns nothing, thus making my table with id #avail-courses blank.

Am I missing something here? I suspect that, in js file, I cannot pass in a collection directly.

For completeness, my partial _avail_course.html.erb is:

<tr>
  <td><%= avail_course.title %></td>
  <td><%= avail_course.note %></td>
  <td><%= link_to 'Info', 'course_list/info/' + avail_course.id.to_s %></td>
  <td><%= button_to 'Enroll', 'course_list/enroll/' + avail_course.id.to_s, method: :put, remote: true %></td>
</tr>

Any input is appreciated.


Solution

  • I found out the issue. It was because @courses has not been defined in the controller. In a normal format.html response, the redirect_to takes care of @courses, but I forgot that a format.js does not invoke another controller.