简体   繁体   English

Ruby on Rails-同时调用html.erb和js.erb

[英]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. 我的目标是使用相同的控制器调用html.erb和js.erb文件,但它仅调用我的html文件。
My js is not called. 我的js没有被调用。
controller/categories_controller.rb 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 查看/类别/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) views / categories / index.js.erb(问题在这里,未调用此文件)

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 . 控制器以请求所要求的格式进行响应,因此,您的链接要求使用HTML而不是JS,因此控制器以.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 . 您的请求将要求JS(因为remote: true属性),并且控制器将以.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. 它将自动找到index.js.erb文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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