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
Thanks in advance.
There is lot of confusion around PATCH as well, I personally agree how JSON API standard is proposing to do it http://jsonapi.org/format/#crud-updating:
I love Rails I but truth is it's not entirely following some core Web conventions. Rails is trying to be productive and too strict conventions are holding down the productivity. So don't go overboard when seeking answer for this. Truth is that Rails is treating PUT and PATCH the same way, and apparently both are wrong. So I recommend:
But if your entire project is using PUT everywhere, you don't need to go through and change everything. Just stick to one or the other (PUT or the PATCH).
UPDATE
I've wrote 2 articles on this topic where I go in depth of this topic.
Rails by default aims to use HTTP verbs in the manner laid out by the REST specification, you should not be concerned as to why the methods may allow you to carry out the same action. Instead you should think about providing an API that is RESTful and that users will understand. These default behaviour can be overridden.
REST denotes that:
A request using the POST method should act upon the resource collection; adding a new resource to the collection Example URL: http://example.com/resources
A request using the PUT HTTP verb should act upon a single resource within the collection; replacing the resource wholly upon the server Example URL: http://example.com/resource/1
A request using the PATCH HTTP verb should act upon a single resource within the collection; updating certain attributes upon the resource where it stands Example URL: http://example.com/resource/1
Rails 4 now makes use of the PATCH verb over the PUT verb for updating a resource.
According to rails convention,
PUT is used for updating an existing resource
POST is used for creating a new resource
In rails 4, PUT has been changed to PATCH to avoid confusion.
Rails generated routes will look like below by default
Notice the action for PUT and POST
PUT and POST are HTTP methods.
In the routes.rb you have to map method and controller#action. In your class you define 3 times the same method. So if you want map these actions to a HTTP method you can't.
You going to change the name of each method and change the implementation to the model class.