开发者

Rails: Do the benefits of using resource based routing to create RESTful controllers outweigh the additional complexity?

开发者 https://www.devze.com 2022-12-19 03:45 出处:网络
I am building a web application using Rails and my first instinct was to make all the controllers RESTful. In particular, I am using the PUT method for any actions that modify data.

I am building a web application using Rails and my first instinct was to make all the controllers RESTful. In particular, I am using the PUT method for any actions that modify data.

But this seems to add unnecessary complexity for a browser-based app because Rails uses Javascript to wrap the URL in a POST request.

Secondly, it means I have to specify the method whenever I create the link for a (non-standard) action. For example, when I have added the “extra” action to the ThingController I need to have the :method => :put in...

link_to "Action", things_extra_url(thing), :method => :put

Finally, it doesn’t seem very DRY to create this mapping for the additional action in routes.rb...

map.resources :things, :member => { :extra =>:put }

Now I have to think about the definition of the extra action in two places.

Is resource based routing intended more for building web services APIs than user interface logic? Is it overkill to use it when building a UI front en开发者_运维技巧d?

In general I agree with the benefits mentioned in this thread - consistency across controllers is a good thing, and the constraints of REST lead to simple, cleaner designs. I do worry a little that forcing some things into REST might be unnatural.

But I'm not really asking about the design philosophy as much as wondering what folks think about this trade-off in Rails specifically. Do the benefits outweigh the additional complexity?


I would encourage REST for web services APIs or not. Thinking in terms of resources helps simplify your code and make it more understandable. Coding via convention is a powerful concept and at the heart of rails. It helps that the REST convention is well understood outside of rails. There will of course be exceptions, but often what you think are exceptions are in fact their own resources. This is the power of the concept. If you run into inconveniences, by all means, define your own route. The "extra" example you gave is a little fishy, I don't think :put is required for "members". Remember that member methods require a reference to an existing resource:

link_to "Action", things_extra_url(thing)

Collections are often confused with members are defined like:

map.resources :things, :collection => { :extra =>:get }

These do not require reference to an existing resource.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号