0

My goal is to call a html.erb and a js.erb file with the same controller but it does only call my html file.
My js is not called.
controller/categories_controller.rb

  def index
    respond_to do |format|
      format.html
      format.js
    end
    @categories = Category.order('name ASC')
    @category = params[:category]
end

view/categories/index.html.erb

<% @categories.each do |c| %>
  <%= link_to c.name, show_category_path(category: c.id), :id => "btn-filter#{c.id}" %>
<% end %>

views/categories/index.js.erb (The problem is here, this file is not called)

alert("test");
$("#btn-filter<%=@category%>").attr("class","active");
KingOfBabu
  • 409
  • 3
  • 21
  • [here](http://stackoverflow.com/questions/9492362/rails-how-does-the-respond-to-block-work) you can find a clarifier discussion. – rfellons Apr 22 '17 at 14:50
  • Another interesting discussion [here](http://stackoverflow.com/questions/43558477/render-different-show-pages-with-category-in-ruby-on-rails) – rfellons Apr 22 '17 at 14:56

3 Answers3

3

The controller responds with the format that the request asks for, so, your link asks for HTML, not JS, thus the controller responds with .html.erb. If you add a call, like this:

<%= link_to c.name, show_category_path(category: c.id), :id => "btn-filter#{c.id}", remote: true %>

Your request will ask for JS (because of the remote: true attribute) and the controller will respond with .js.erb.

Gerry
  • 10,337
  • 3
  • 31
  • 40
1
You should add remote: true option

<% @categories.each do |c| %>
  <%= link_to c.name, show_category_path(category: c.id),remote:true, :id => "btn-filter#{c.id}" %>
<% end %>

it will automatically find index.js.erb file.

TheVinspro
  • 361
  • 1
  • 4
  • 17
1

Just add a remote: true attribute to link_to.