Rails 3,自定义操作和HTML请求方法 [英] Rails 3, Custom Actions, and HTML request methods

查看:88
本文介绍了Rails 3,自定义操作和HTML请求方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不了解使用postvsgetvsput请求,自定义控制器操作以及是否使用链接或表单/按钮的专业人士和骗局。

I don't really understand the pro's and con's of using "post" vs "get" vs "put" requests, on custom controller actions, and whether to use links or forms/buttons.

因此,假设我有一个简单的待办事项列表,包含任务和任务控制器,我想要一个完整的操作,我在其中找到一个特定的任务db并将其状态属性从不完整更新为完成。

So let's say I have a simple to-do list with tasks, and a tasks controller, and I want a "complete" action where I find a specific task in the db and update it's status attribute from "incomplete" to "complete."

def complete
  @task = Task.find(params[:id])
  if @task.update_attributes(:status => "complete")
    redirect_to tasks_url, :notice => "Completed!"
  else 
    redirect_to tasks_url, :error => "Whoops."
  end
end

定义此路线的最佳做法是什么,我应该使用HTML请求方法(post?put?get?),我应该使用普通链接还是表单? (并注意:假设我的用户安全模型都是用设计计算出来的,在过滤器之前是合适的,等等。)

What's the best practice way to define this route, which HTML request method should I use (post? put? get?), and should I use a plain link or a form? (and note: assume my user security model is all figured out with devise, and appropriate before filters, etc.)

最重要的是,我将如何表达这一切在一个Rails 3 routes.rb文件?

And most of all, how would I articulate all this in a Rails 3 routes.rb file?

注意,下面的代码对我来说并不适用:

Note, the below code wasn't really working for me:

#routes.rb
resources :tasks do
   members do
     post 'complete'
   end
end

所以目前我正在使用它:

so currently I'm using this instead:

#routes.rb
match 'tasks/:id/complete', 'tasks#complete', :as => "complete_task"

#view
= link_to "Complete", complete_task_path(:id => @task.id)

但这会触发get请求,我觉得它应该是put或post。或者它应该是一个链接?它应该是一个隐藏字段的表单吗?

But this triggers a get request, and I feel like it should be a "put" or a "post." Or should it be a link at all? Should it be a form with hidden fields?

推荐答案

link_to方法通常会生成一个锚标记,即< a>< ; / a>,即常规GET请求

"link_to" method usually generates an anchor tag ie "<a></a>", ie a regular GET request

使用link_to执行POST请求您应该执行以下操作

to do a POST request using link_to you should do the following


= link_to "Complete", complete_task_path(:id => @task.id), :method => :post

请记住,如果在浏览器中禁用了javascript,则上述语句将回退到GET请求而不是POST。

Remember if javascript is disabled in the browser, the above statement will fall back to a GET request instead of POST.

这篇关于Rails 3,自定义操作和HTML请求方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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