Ruby on Rails link_to with put 方法 [英] Ruby on Rails link_to With put Method

查看:46
本文介绍了Ruby on Rails link_to with put 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 的新手,我正在尝试使用 link_to 帮助程序创建一个链接,该链接发出 PUT 请求而不是 GET 请求.具体来说,我正在尝试创建一个链接,用于从管理面板激活我的应用程序中的用户帐户.我使用的是 Rails 3.0.5.

我的 routes.rb 文件有:

匹配'/admin/users/:id/activate' =>'admin#activate_user',:动作=>:activate_user, :via =>:放

我的观点有:

link_to 'Activate', :action =>:activate_user, :id =>user.id, :method =>:放

但是这会生成 URL(例如)/admin/users/7/activate?method=put 和源代码 <a href="/admin/users/7/activate?method=put">激活.

相反,我想生成 Activate

我意识到我可以使用 button_to,但我已经与这个问题搏斗了一段时间,我很困惑为什么我会看到这种行为,而其他教程说我所做的应该是有效的.我如何着手创建具有我想要的行为的 link_to 助手?

解决方案

Updated - link_to 助手将执行 GET,除非指定了方法.

最好在路由文件中指定确切的请求类型,而不是 match.如何将 match 替换为 put 在路由中为:

put '/admin/users/:id/activate' =>'admins#activate_user', :as =>'激活_用户'link_to 'Activate', activate_user_path(user.id), 方法: :put

activate_user 方法应该驻留在 admins 控制器中.docs 有关于 的更多信息link_to 助手.

I'm new to Rails, and I'm trying to use the link_to helper to create a link that issues a PUT request instead of a GET request. Specifically, I'm trying to create a link that activates a user's account in my app from the admin's panel. I'm using Rails 3.0.5.

My routes.rb file has:

match '/admin/users/:id/activate' => 'admin#activate_user',
  :action => :activate_user, :via => :put

My view has:

link_to 'Activate', :action => :activate_user, :id => user.id, :method => :put

However this generates the URL (for example) /admin/users/7/activate?method=put with the source code <a href="/admin/users/7/activate?method=put">Activate</a>.

I'd like to generate, instead, <a href = "/admin/users/7/activate" data-method="put">Activate</a>

I realize I could use button_to, but I've been wrestling with this issue for a while and I'm confused why I'm seeing this behavior, when other tutorials say that what I'm doing should be valid. How can I go about creating a link_to helper with the behavior I want?

解决方案

Updated - The link_to helper will do a GET unless a method is specified.

Its better specifying the exact request type, instead of match in your routes file. How about replacing match by put in routes as :

put '/admin/users/:id/activate' => 'admins#activate_user', :as => 'activate_user'

link_to 'Activate', activate_user_path(user.id), method: :put

The activate_user method should reside in admins controller. The docs has more info on link_to helper.

这篇关于Ruby on Rails link_to with put 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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