Rails Put vs Post

kem*_*hee 13 post ruby-on-rails http put

我一直在阅读put和post请求之间的区别,我有一些与rails相关的问题:我想更改已经创建的行中的一个特定字段...我应该使用put还是post请求?例如以下不同?

#Assume this is a put request
def update
    @model=Model.find(x)
    @model.field="new_field"
    @model.save
end

#Assume this is a post request
def update
    @model=Model.find(x)
    @model.field="new_field"
    @model.save
end

#What if I use the rails update method?
def update
    @model=Model.find(x)
    @model.update(model_params)
    @model.save
end
Run Code Online (Sandbox Code Playgroud)

提前致谢.

ush*_*sha 20

根据铁路惯例,

PUT用于更新现有资源

POST用于创建新资源

在轨道4中,PUT已更改为PATCH以避免混淆.

Rails生成的路由默认情况下如下所示

    posts GET    /posts(.:format)                            {:action=>"index", :controller=>"posts"}
          POST   /posts(.:format)                            {:action=>"create", :controller=>"posts"}
 new_post GET    /posts/new(.:format)                        {:action=>"new", :controller=>"posts"}
edit_post GET    /posts/:id/edit(.:format)                   {:action=>"edit", :controller=>"posts"}
     post GET    /posts/:id(.:format)                        {:action=>"show", :controller=>"posts"}
          PUT    /posts/:id(.:format)                        {:action=>"update", :controller=>"posts"}
          DELETE /posts/:id(.:format)                        {:action=>"destroy", :controller=>"posts"}
Run Code Online (Sandbox Code Playgroud)

注意PUT和POST的操作


小智 5

默认情况下,Rails旨在以REST规范的方式使用HTTP谓词,您不应该关注为什么这些方法可以允许您执行相同的操作.相反,您应该考虑提供一个RESTful的API并且用户会理解.可以覆盖这些默认行为.

REST表示:

使用POST方法的请求应该对资源集合起作用; 将新资源添加到集合示例URL:http://example.com/resources

使用PUT HTTP动词的请求应该对集合中的单个资源起作用; 完全在服务器上替换资源示例URL:http://example.com/resource/1

使用PATCH HTTP谓词的请求应该对集合中的单个资源起作用; 更新资源所在的某些属性示例URL:http://example.com/resource/1

Rails 4现在利用PUT动词上的PATCH动词来更新资源.