简体   繁体   中英

Ruby on Rails - Call both html.erb and js.erb

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");

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 .

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.

只需向link_to添加一个remote:true属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM