2017-04-22 40 views
0

我的目标是使用相同的控制器调用html.erb和js.erb文件,但它只调用我的html文件。
我的js没有被调用。
控制器/ categories_controller.rbRuby on Rails - 同时调用html.erb和js.erb

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

视图/类别/ index.html.erb

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

视图/类别/ index.js.erb的(该问题是在这里,该文件不叫)

alert("test"); 
$("#btn-filter<%[email protected]%>").attr("class","active"); 
+0

[here](http://stackoverflow.com/questions/9492362/rails-how-does-the-respond-to-block-work)你可以找到澄清的讨论。 – rfellons

+0

另一个有趣的讨论[这里](http://stackoverflow.com/questions/43558477/render-different-show-pages-with-category-in-ruby-on-rails) – rfellons

回答

3

控制器与该请求要求的格式进行应答,因此,您的链接请求HTML,JS没有,因此控制器与响应。如果添加了一个电话,是这样的:

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

你的要求会问JS(因为remote: true属性),控制器将与.js.erb回应。

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 %> 

它会自动找到index.js.erb文件。

1

只需将一个遥控器:true属性添加到link_to。