After I generate a scaffold, Rails gives me the ability to POST to items.xml
which will create a new item
. A GET to items.xml
will simply list them all. Where does Rails specify which method in the controller (create
or index
, respectively) will be called, based on the type of action I am performing?
More specifically, POST calls methodA but GET to the same URL calls methodB. Where is this specified? Where does Rails make the determination to call the index
method of the controller?
By using the post method rather than the get method, Rails will define a route that will only respond to POST methods. The POST method is the typical method used by forms all over the web. You now need to create the create action within the PostsController for this to work.
The Rails router is responsible for redirecting incoming requests to controller actions. The routing module provides URL rewriting in native Ruby. It recognizes URLs and dispatches them as defined in config/routes.
rake routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions. Each action's purpose is to collect information to provide it to a view.
I believe it's specified by REST. Here's a list for ya:
GET /items #=> index GET /items/1 #=> show GET /items/new #=> new GET /items/1/edit #=> edit PUT /items/1 #=> update POST /items #=> create DELETE /items/1 #=> destroy
Edited to add to get all those routes, in config/routes.rb, simply add map.resources :items
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With