How do you route an action to the application controller in Rails 3?

匆匆过客 提交于 2019-12-03 07:10:02

问题


I am using the gem rails3-jquery-autocomplete and had no problems with it, however I have now moved my autocomplete form into the application template and therefore the ajax calls are now being dealt by the application controller, so my routes have changed from:

home/autocomplete_category_name

and now need to have the home removed and the path from:

home_autocomplete_category_name_path

to:

autocomplete_category_name_path

Anybody got any ideas? Still learning the ins and outs of Rails so this is a dead end for me right now.

Thanks.


回答1:


URLs don't map directly to ApplicationController - only subclasses of it.

You need to move the call to autocomplete into another controller. The location of the form shouldn't make a difference, as long as you're passing the correct path when you define your text_field




回答2:


Old post, but the accepted answer is wrong. Though the spirit of it is right - you should probably move your method to a more appropriate controller; but if you insist on having the method in application_controller.rb

# routes.rb
match '/some_route', to: 'application#some_route', as: :some_route

...will route to the 'some_route' method in application_controller.rb.




回答3:


Another necro but there is a more DRY friendly way to do this, compared to pavling's solution

get :autocomplete_category_name, controller:"application"

I was trying(yesterday) to move it to the Application controller to try to reuse code better and not tie it to a specific controller. Only today did I realize that makes no sense, since the controller used to answer this call is going to be a completely different object to the controller rendering the view anyway..




回答4:


Using Rails 4, your have to use get, not match...

# routes.rb
get '/autocomplete_category_name', to: 'application#autocomplete_category_name', as: :autocomplete_category_name



回答5:


try something like

match "home/autocomplete_category_name", "home#autocomplete_category_name", :as => "autocomplete_category_name"



回答6:


In Rails 4, use this:

get 'application/autocomplete_category_name', as: 'autocomplete_category_name'

You have 'autocomplete_category_name_path' to you links



来源:https://stackoverflow.com/questions/4778301/how-do-you-route-an-action-to-the-application-controller-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!