I want to add a new update(new_update) action in my user model of rails which will update a single column in the model. which rest api method I should use in routes file. Should I use put or patch or both.
resources: users do
member do
put 'new_update'
patch 'new_update'
end
If you want to match 100% with the HTTP verb definition.
PUT is supposed to overwrite your targeted resource entirely with the content in the request(all field non present in the request should be set to removed/nullified).
PATCH is supposed to only modify the fields sent in the request.
That being said, most of the time people don't make the difference and use either of them (a lot of people don't even know that there is a PATCH verb) is use PUT with the same behavior as PATCH (since the use case for PUT is quite rare on imo).
Related
In rails the routes can be created using
resources :vehicals
so, that will create many routes which will produce the basic routes required for the CRUD operation, But I am confused between the 2 routes i.e.
PATCH /vehicals/:id(.:format) vehicals#update
PUT /vehicals/:id(.:format) vehicals#update
please clear which is to use while update.
In rails there's no effective difference, and you can see from your routes that they call the same controller action.
Because rails only updates fields that are included in the view form and leaves other fields unchanged, it effectively has always implemented "PATCH" logic even before 'PATCH' was ever officially introduced.
Current Rails forms default to method post for sending new records and patch for updating existing records.
When creating or updating a resource, the target URL by default is the same like the index route, for users e.g. localhost:3000/users.
The difference is that instead of POST, PUT method is used (as far as I know).
I find this suboptimal. For example, when having a navigation menu with an item "Create user" in it, I want to set the active CSS class when the item is active. I do this by comparing current_page? to the menu item's URL (e.g. users/new). This works fine, but only when I don't have validation errors. In this case, the URL now isn't users/new anymore, but users.
Is there a good reason why Rails doesn't point to users/new (or users/edit) respectively for POST/PUT requests? Are there any downsides to using them? Is there an easy way to change this behaviour?
The reason is REST.
In a nutshell, Rails treats everything as a resource, and there are conventions followed in order to do so. In a typical CRUD application, you have the Create (POST), Read (GET), Update (PUT/PATCH), and Destroy (DELETE) actions, which are the verbs used to act on resources.
Let's say you have a User resource. A list of users would be found at /users. An individual user, being an individual object of a resource, would then be found at /users/1, where "1" is the identifier of the resource in question.
Now, based on the CRUD verbs available to you, if you wanted to edit a user, what ACTION makes the most sense given the CRUD verbs we talked about? PUT /users/1 is the correct answer; you're updating (the U in CRUD) a particular resource. If you wanted to delete that user? DELETE /users/1 makes sense. If you want to create one? CREATE /users is the logical choice, because you're not acting on a particular object, but on the resource as a whole, similar to GET /users not acting on an individual object, but a collection.
/users/new is a path to a page that will let you do that, but it doesn't mean it should make the CREATE request to /users/new, because "new" doesn't describe a resource the same way.
I have an additional method in one of my otherwise restfull controllers called 'importdata'. As I'm actually changing the data (importing csv in the database), I understood that it should be a put route instead of get.
Initially I had
resource data_set do
put 'importdata', on: :method
end
what I also tried is:
put 'data_sets/:id/importdata', "data_sets#importdata'
rake routes shows the route I want in both cases.
What I did when I had the method on (1st example) route in the controller was
redirect_to import_data_sets_path id: dataset.id
And with the second example:
redirect_to controller: "data_sets", action: "importdata", id: dataset.id
The message I get in both cases is:
No route matches [GET] "/data_sets/28/importdata"
Which is correct, because it's a put route. The only way I get this to work is to change the put for a get:
get 'data_sets/:id/importdata', "data_sets#importdata'
How can I get that to work on a put route? Should it be a put route in the first place?
Thanks for your time.
Simply put you can't 'upgrade' a HTTP request issued by an user. redirects only work over GET. If the user is changing something do it through a form and make sure it's a PUT request as you're modifying an existing resource.
If the PUT is conditional there's several options, either figure out how to solve this in the UI, use an HTTP client to issue the PUT(which doesn't make sense for an local call) or extract the editing of the resource in some other kind of class and use it in the controller.
However, even if the edit is optional it makes more sense to let the user fire a PUT in the first place.
Hope that helps.
I'm doing a rewrite of an old Rails application and I thought I should do it in a RESTful manner, as a learning experience if nothing else.
I've reached some actions that toggles a boolean value, for example if an article is published or not.
Before I had a couple of actions: toggle_published, publish and unpublish.
They were very easy to use: i just made a link to them in the article-list.
How would you do the same thing in a RESTful manner?
Should I use the update-action, and build a mini-form to replace each link that I used before? I don't particulary like that idea.
Just a notice:
A toggle method is not RESTful, because the HTTP PUT verb is supposed to be idempotent (see a.o. http://en.wikipedia.org/wiki/Idempotence#Examples). This means that no matter how often you execute a method, it should always give the same result. A toggle method does not adhere to this principle, as it does not give the same result if you execute it once comparing to executing it twice.
If you want to make it RESTful, you should create two methods: one for setting and one for unsetting.
Making an application RESTful does not only mean that you should use the correct HTTP verb.
I'd probably solve it with PUT/DELETE or POST/DELETE on a nested "toggle resource". Perhaps not 100% completely restful but certainly easy enough to understand.
PUT or POST /articles/:id/published # Toggle published ON
DELETE /articles/:id/published # Toggle published OFF
GET /articles/:id/published # Get state RESTfully via status 200 (ON) or 404 (OFF)
Might seem a bit odd, but it is technically RESTful.
Update: A (perhaps) more natural approach might also just be:
PUT or POST /articles/:id/published Data: { state: true/false } # Toggle published ON
You could also use the PATCH verb with the actual article which I assume has a published property:
PATCH /articles/:id { published: true/false }
Because all the cool REST kids are using PATCH nowadays.
It sounds like you have two use cases:
set published state
toggle published state
You should be able to add a member route for the toggle action for:
/articles/<id>/toggle_published - calls Article.toggle(:published)
And use Article update on :published attribute via the standard REST resource route.
map.resources :articles, :member => :toggle
I like #Van der Hoorn answer
so in real life we are using in login & logout scenario
use post or put or patch
/users/login -> with some payload data
/users/logout
In Above Eg login & logout is almost acting like setting boolean Flag , Easy to read and set in db
Eg : so its no harm to use same idea in toggle context
use post or put or patch
/book/3/publish
/book/4/unpublish
Note . :
1 : use this approach if there is only 1 field to be toggled , else if there are multiple fields then general /book/4 a patch request with payload data will do
2 : use this approach if there is any security layer is implemented so it will be like
Eg :
Editor -> can access urls like `/books/:id` & `/books/:id/publish`
Senior Editor -> can access urls like `/books/:id` & `/books/:id/unpublish`
new_story GET /story/new(.:format) {:action=>"new", :controller=>"stories"}
edit_story GET /story/edit(.:format) {:action=>"edit", :controller=>"stories"}
story GET /story(.:format) {:action=>"show", :controller=>"stories"}
PUT /story(.:format) {:action=>"update", :controller=>"stories"}
DELETE /story(.:format) {:action=>"destroy", :controller=>"stories"}
POST /story(.:format) {:action=>"create", :controller=>"stories"}
In web development I have done with other technologies, I only ever used GET and POST methods, but with RESTful routes in Rails, by default the PUT and DELETE methods are used for the update and destroy actions. What's the advantage or need for using PUT and DELETE? I assume these methods are just another way of doing POST - but why not just stick with POST?
The advantage is mostly semantic, and can also simplify URLs to an extent. The different HTTP methods map to different actions:
POST => create a new object
DELETE => delete an object
PUT => modify an object
GET => view an object
Then, in theory, you can use the same URL, but interact with it using different methods; the method used to access the resource defines the actual type of operation.
In practice, though, most browsers only support HTTP GET and POST. Rails uses some "trickery" in HTML forms to act as though a PUT or DELETE request was sent, even though Rails is still using GET or POST for these methods. (This explains why you might not have used DELETE or PUT on other platforms.)
I just wanted to add something to the accepted answer because his definition of the http verbs are incorrect. They all have a spec which "should" be followed and you can create/update/delete with multiple http verbs based on the specs.
I am going to highlight some of the important bits in the RFC 2616 by W3
I'm going to start with PUT because in my opinion it has the most confusion surrounding it.
PUT is used for both create/update PUT updates by completely replacing the resource on the server with the resource sent in the request
For example
You make this call to my api
PUT /api/person
{
Name: John,
email: jdoe#hra.com
}
my Server has this resource living on the server
{
Name: Jane,
email: jdoe#hra.com
}
Now my existing resource is completely replaced by what you sent over and this is what I have on my server.
{
Name: John,
email: jdoe#hra.com
}
So if you PUT and only send an email in the body
PUT /api/person
{
email: jdoe#hra.com
}
My Server will completely replace the entity
{
Name: Jane,
email: jdoe#hra.com
}
With
{
email: jdoe#hra.com
}
And Name will be gone. Partial updates are for PATCH but I use POST for that anyway.
One of the main reasons why we create/update with put is because it is idempotent.
It's just a fancy term and the basic definition of it is multiple identical requests are the same for a single request.
Example
Suppose I PUT a file to api/file if the origin server does not find that file it will create one. If it does find a file it will completely replace the old file with the one I sent over. This ensures that one file is ever created and updated. If no file exists and you call PUT 5 times, the first time it creates a file then the other 4 times it replaces the file with what you send over. If you call a POST 5 times to create it will create 5 files.
You PUT to that exact URI. If you don't you have to send a 301 (Moved Permanently) to the user and allow then make a choice whether or not to redirect the request. Most times the server you PUT to usually hosts the resource and takes care of updating it
Those are the major points in when to use PUT
As far as POST is concerned
You can also create/update and then some...
As I mentioned above there are a few key differences.
Post is more General. In what ways? some other examples include a gateway to other protocols, it could take the response and send it to some data handler out in the middle of yonder, or it can extend some sort of functionality.
Post doesn't have the restriction of "To the exact URI or notifiy" for examplePOST can append a resource to an existing collection and decide where it's stored.
Now what about Delete Why don't I just POST?
When you DELETE, the server SHOULD NOT respond with success unless you delete the resource or move it to an inaccessible location at the time the response is sent.
Why is that important? What if you call DELETE but the resource has to go through "APPROVAL" before being deleted? If the delete can be rejected you can't send a successful error code and if you do follow the basic specs on this it's confusing to the caller. Just an example I'm sure you can think of many others.
I just highlighted some of the major points on when to use the common Http verbs
Here's the "methods" section of the HTTP 1.1 spec; it defines lots of methods, and they all have different benefits and tradeoffs. POST is the most flexible, but the tradeoffs are numerous: it's not cacheable (so the rest of the internet can't help you scale), it isn't safe or idempotent so the client can't just resend it gets an error, and it is no longer clear exactly what you're trying to accomplish (because it's so flexible). I'm sure there are others but that ought to be sufficient. Given all that, if the HTTP spec defines a method that does exactly what you want your request to do, there's no reason to send a POST instead.
The reason POST is so common is that, historically at least, web browsers only supported GET and POST. Since GET is defined to be safe and idempotent (even though many applications don't adhere to that), the only safe way to modify data was to send a POST. With the rise of AJAX and non-browser clients, that is no longer true.
BTW, the mapping #mipadi gave is the standard mapping, but it isn't the only valid one. Amazon S3, for instance, uses PUT to create resources. The only reason to use POST is if the client doesn't have sufficient knowledge to create the resource, e.g., you back your resources with a relational database and use artificial surrogate keys.
That'd be kind of like asking why "delete" a file when you could just set its contents to zero bytes and the file system would just treat that as a delete. HTTP has supported verbs other than GET/POST forever but the way SOAP evolved kinda twisted the original meaning of those verbs. REST is a simpler, back to basics approach that uses the verbs as they were intended instead of inventing some new verb concept inside of the payload.