3.4 Routing and CRUD
3.4.1 REST Resources and Rails
Like most of Rails, support for RESTful applications is “opinionated”; that is, it offers a particular way of designing a REST interface, and the more you play along, the more convenience you reap from it. Most Rails applications are database-backed, and the Rails take on REST tends to associate a resource very closely with an Active Record model, or a model/controller stack.
3.4.2 From Named Routes to REST Support
When we first looked at named routes, we saw examples where we consolidated things into a route name. By creating a route like
get 'auctions/:id' => "auction#show", as: 'auction'
#with this route, you gain the ability to use nice helper methods in situations like:
link_to item.description, aution_path(item.auction)
Well, we’ve used up the route name auction_path
on the show action. We could make up names like auction_delete_path
and auction_create_path
but those are cumbersome. We really want to be able to make a call to auction_path
and have it mean different things, depending on which action we want the URL to point to.
We could differentiate between the singular (auction_path
) and the plural (auctions_path
). A singular URL makes sense, semantically, when you’re doing something with a single, existing auction object. If you’re doing something with auctions in general, the plural makes more sense.
3.4.3 Reenter the HTTP Verb
Form submissions are POSTs by default. Index actions are GETs. That means that we need to get the routing system to realize that:
/auctions submitted in a GET request
versus /auctions submitted in a POST request!
are two different things.
This is what the REST facility of Rails routing does for you. It allows you to stipulate that you want /auctions routed differently, depending on the HTTP request method. It lets you define named routes with the same name, but with intelligence about their HTTP verbs. In short, it uses HTTP verbs to provide that extra data slot necessary to achieve everything you want to achieve in a concise way, by:
# in routes.rb
resources :auctions
网友评论