I am following a neat ruby on rails tutorial about routes. So I am wondering, how does routing know so much?
I have one controller called posts_controller, and a post model. In the routes.rb file, I added
# config/routes.rb
resources :posts
As far as I understood it, this automatically creates the appropriate routings for all the controller actions associated with a post. So far, I have only one method in my posts_controller:
# app/controllers/posts_controller.rb
def index
end
But strangely, when I execute
$ rake routes
it gives me all this:
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
How does the routing mechanism know so much without ever telling it that I want to able to create and update posts?
Using “resources” has nothing to do with the actions you have defined. It simply creates all of the restful routes you could need in your controller.
As you can see it creates: index, create, new, edit, show, update, and destroy
It’s actually unintelligent since it creates routes for actions which don’t exist.
An example of how to limit it to only actions you need.