我想从link_to
我尝试过:
<% @categories.each do |category| %>
<tr><td>
<%= link_to category, :controller => "movies", :action => "show_category", :category => category, :method => :post, :remote => true%>
</td></tr>
<% end %>
这是我完整的routes.rb
文件:
Rails.application.routes.draw do
resources :movies
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: "movies#index"
post '/movies/show_category', to: 'movies#show_category', as: 'show_movies_by_category'
end
这是我在movies_controller
中的目标函数,我想在单击link_to
时被调用(我的理解是从这个函数中,我可以调用show_category.js.erb
Javascript文件):< / p>
def show_category
respond_to do |format|
format.js {render layout: false}
end
end
但是似乎未调用movies_controller#show_category
,而是调用了movies_controller#show
。这是我在Rails控制台中看到的:
Started GET "/movies/show_category?category=Romance&method=post" for 127.0.0.1 at 2019-01-06 13:41:47 +0530
Processing by MoviesController#show as JS
Parameters: {"category"=>"Romance", "method"=>"post", "id"=>"show_category"}
Movie Load (0.4ms) SELECT "movies".* FROM "movies" WHERE "movies"."id" = ? LIMIT ? [["id", 0], ["LIMIT", 1]]
↳ app/controllers/movies_controller.rb:87
Completed 404 Not Found in 6ms (ActiveRecord: 0.4ms)
ActiveRecord::RecordNotFound (Couldn't find Movie with 'id'=show_category):
app/controllers/movies_controller.rb:87:in `set_movie'
我在这里做什么错了?
答案 0 :(得分:0)
问题似乎与路由有关。您的"/movies/show_category/<...>"
请求被解析为movies/:id
,并且id
参数被设置为show_category
。
由于您的movies
路由被定义为资源路由(resources movies
),因此解决此问题的方法是将show_category
路由定义为资源中的附加操作:< / p>
resources :movies do
post :show_category, on: :collection
end
此外,您似乎在方法上不匹配。您在route.rb中将操作列为POST,但您正在使用GET方法。我认为问题出在您的link_to
电话中:您应该写method: :post
而不是data: { method: :post }
。
这应该解决它。有关更多信息,请查看Rails routing guide,特别是Adding RESTful actions部分。
答案 1 :(得分:0)
更改为:
查看:
<% @categories.each do |category| %>
<tr><td>
<%= link_to show_category, :remote => true do %>
Show Category
<% end %>
</td></tr>
<% end %>
路线:
get 'show_category', to: 'movies#show_category', as: 'show_category'
您不需要控制器中的response_to。您可以删除所有内容。
这将调用show_category.js.erb