2017-04-22 39 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。