Rails Put vs Post [英] Rails Put vs Post
问题描述
我一直在阅读put和post请求之间的区别,我有一些与rails相关的问题:我想更改已创建的行中的一个特定字段...我应该使用put还是一个帖子请求?例如,以下是不同的?
I have been reading up on the difference between put and post requests and I have some related questions as it pertains to rails: I would like to change one specific field in an already created row...should I use a put or a post request? For example are the following different?
#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
提前致谢。
推荐答案
根据rails惯例,
PUT用于更新现有资源
PUT is used for updating an existing resource
POST用于创建新资源
POST is used for creating a new resource
在rails 4中,PUT已更改为PATCH以避免混淆。
In rails 4, PUT has been changed to PATCH to avoid confusion.
Rails生成的路由将默认情况下如下所示
Rails generated routes will look like below by default
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"}
注意PUT和POST的操作
Notice the action for PUT and POST
这篇关于Rails Put vs Post的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!