Rails: RESTful resources: Worth using or inflexible/overrated?
I've been messing about in rails the past 2 months and so far everything's going well - but there's one area I'm a little doubtful on.
I keep hearing about the joys of RESTful rails resources: that is, a 'resource :foo' in config/routes, and your 7 restful actions in the controller.
Except for very simple things (eg stuff that's 99% done by running 'generate scaffold'), I find it's less convenient to try squeeze my project functionality into that approach than to just match urls in config/routes one-by-one and do each action as needed.
But I keep getting the sense that I'm wrong, and that in all but the most extreme circumstances, RESTful resources are the way to go.
So:
(a) Can anyone offer an o开发者_如何学Gopinion on this?
(b) For experienced rails folks, what % of your routes in a typical project are :resources and what % are coded action-by-action? Cheers...
Resources are convenient, but they are not a "one size fits all" feature. Some things just don't make sense with the 7 methods.
Keep in mind that you can:
- Exclude specific methods with
:except
. - Include only specific methods with
:only
. - Add your own methods to the resource.
So they aren't as inflexible as you may think. But if, after taking those 3 points in mind, the resource just doesn't "feel right", skip it! REST was never meant to replace regular routing, it just tries to abstract away the most common use case.
If you skip out on RESTful resources completely, you'll be missing a ton of free functionality. Use it wisely and you'll be fine.
Generally I start a project with the REST architecture in mind. I build out my basic functionality this way, but as the project/website progresses I write more and more views that do not fit into the RESTful architecture. Marketing sites and parallel functionality are perfect examples of this.
Here is an article on the approach:
http://ablogaboutcode.com/2010/11/22/to-be-or-not-to-be-restful-ruby-on-rails-best-practices/
Before you get started, here are some questions you might want to ask yourself:
- Does this controller/view deal primarily with an object/entity like a Post, Blog?
- Are create, update, delete, edit and new actions all going to be available on the web?
As a guideline, if you answer YES to these two questions, then it’s probably best to start with REST and expect that you will eventually use the architecture as a building block for additional actions and views you might want to perform. Otherwise, pick a URL that best represents what the action will show or do (/archives, /tour, /december-offer) and make sure you use the proper HTTP Protocols (GET for display, PUT for update, DELETE for removing and POST for creating).
精彩评论