在控制器中执行操作的 Rails 3 链接或按钮 [英] Rails 3 link or button that executes action in controller

查看:21
本文介绍了在控制器中执行操作的 Rails 3 链接或按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 RoR 3 中,我只想有一个链接/按钮来激活控制器中的某些操作/方法.具体来说,如果我点击页面上的update_specs"链接,它应该转到我的产品控制器中的update_specs"方法.我在此网站上找到了执行此操作的建议:

In RoR 3, I just want to have a link/button that activates some action/method in the controller. Specifically, if I click on a 'update_specs' link on a page, it should go to 'update_specs' method in my products controller. I've found suggestions to do this on this site:

link_to "Update Specs", :controller => :products, :action => :update_specs

但是,当我单击此链接时出现以下路由错误:

However, I get the following routing error when I click on this link:

路由错误没有路由匹配 {:action=>"update_specs",:controller="products"}

Routing Error No route matches {:action=>"update_specs", :controller=>"products"}

我已经阅读了路由,但我不明白如果所有其他方法都可以通过 resources:products 访问,我为什么必须路由这个方法.

I've read up on routing but I don't understand why I should have to route this method if all other methods are accessible via resources:products.

推荐答案

您需要为其创建路由.

例如:

resources :products do
  put :update_specs, :on => :collection
end

默认情况下,link_to 会在你的路由中寻找 GET 方法.如果要处理 POSTPUT 方法,则需要通过添加 {:method =>:post }{:method =>:put } 作为参数,如:

Also by default link_to will look for a GET method in your routes. If you want to handle a POST or PUT method you need to specify it by adding {:method => :post } or {:method => :put } as a parameter, like:

link_to "Update Specs", {:controller => :products, :action => :update_specs}, {:method => :put }

或者您可以使用 button_to 而不是 link_to,后者默认处理 POST 方法.

Or you can use button_to instead of link_to which handles the POST method by default.

这篇关于在控制器中执行操作的 Rails 3 链接或按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆