简体   繁体   English

如何将操作路由到Rails 3中的应用程序控制器?

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

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: 我正在使用gem rails3-jquery-autocomplete并且没有任何问题,但是我现在已经将自动完成表单移动到应用程序模板中,因此ajax调用现在由应用程序控制器处理,因此我的路由已从以下更改:

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. 还在学习Rails的来龙去脉,所以现在这对我来说是个死胡同。

Thanks. 谢谢。

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 但是如果你坚持在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. ...将路由到application_controller.rb中的'some_route'方法。

URLs don't map directly to ApplicationController - only subclasses of it. URL不直接映射到ApplicationController - 只是它的子类。

You need to move the call to autocomplete into another controller. 您需要将调用autocomplete移动到另一个控制器。 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 只要您在定义text_field时传递正确的路径,表单的位置就不会产生影响

Another necro but there is a more DRY friendly way to do this, compared to pavling's solution 与pavling的解决方案相比,还有一种更加干燥的方法可以做到这一点

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.. 直到今天我才意识到这没有任何意义,因为用于回答此调用的控制器将成为控制器呈现视图的完全不同的对象。

Using Rails 4, your have to use get, not match... 使用Rails 4,你必须使用get,而不是匹配...

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

尝试类似的东西

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

In Rails 4, use this: 在Rails 4中,使用:

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

You have 'autocomplete_category_name_path' to you links 您有'autocomplete_category_name_path'链接

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

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