Take the most simple example:
map.resource:account
1) How different is it from defining all the names routes - like:
:map.new_ac开发者_运维问答count "new_account", :controller=>"activity", :action=>"new"
2) How do you set an additional route within the resource definition? For example, say there is one more method for the resource
:map.brand_new_action "brand_new_action", :controller=>"activity", :action=>"brand_new_action"
Do we just add it below? But that seems to defeat the point of the resource
How different is it from defining all the routes manually?
It's not different, in that it's more of a convenience. Why would you want to define all your routes by hand, that can be quite tedious. So the common CRUD actions are mapped automatically, below is an example using a contacts controller:
map.resources :contacts
... or in Rails 3 ...
resources :contacts
http_verb - action - route
GET - index - /contacts
GET - show - /contacts/5
GET - new - /contacts/new
POST - create - /contacts/create
GET - edit - /contacts/5/edit
PUT - update - /contacts/5
DELETE - destroy - /contacts/5
These are commonly referred to as the "7 Restful Actions," however you can add your own custom routes if needed (although you're strongly encouraged to use the 7 whenever possible).
How do you add additional resources/routes?
Adding additional routes is easy. First you want to decide if you're working with a collection or a specific member, then also consider if the action is creating or updating something. For update actions you want to use PUT, create POST, destroying uses DELETE, and anything else is probably a GET.
map.resources :contacts, :collection => { :new_this_month => :get },
:member => { :make_featured_person => :put }
... or in Rails 3 ...
resources :contacts do
collection do
get 'new_this_month'
end
member do
put 'make_featured_person'
end
end
http_verb - action - route
GET - new_this_month - /contacts/new_this_month
PUT - make_featured_person - /contacts/5/make_featured_person
Most of the time the 7 Restful Actions are plenty enough, but in some situations you'll need custom routes. This is why Rails handles the most common case and gives you the ability to handle unique cases.
Resource routes simple supply a shorthand way to generate the most common routes found in a controller, that is create, read, update and delete CRUD. This allows customisation because that is likely to be what people will need.
To add an additional route to a resource specification:
map.resources :accounts, :collection => {:administrate => :get}, :member => {:activate => :put}
:collection results in something like:
/accounts/administrate
:member likewise:
/accounts/123/activate
http://guides.rubyonrails.org/routing.html#restful-routing-the-rails-default
精彩评论