Rails POST, PUT, GET

2019-01-21 01:51发布

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?

8条回答
我命由我不由天
2楼-- · 2019-01-21 02:27

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

查看更多
Evening l夕情丶
3楼-- · 2019-01-21 02:32

The best place to learn about this would be the Routing Guide.

查看更多
4楼-- · 2019-01-21 02:34

This will help a lot, but it's not a direct answer to your question. The following command will list the mappings your app uses so you don't have to remember all the details or guess.

$ rake routes

To answer more directly, this is a convention that rails uses. You set this mapping up when you put something like the following in your routes.rb

map.resources :items
查看更多
虎瘦雄心在
5楼-- · 2019-01-21 02:34

To be honest, you can't really go wrong with the routing documentation on the Rails website. This has helped take the next steps and move beyond the comfort of resources (which for most apps is fine)and really nail down the solid routing features available.

http://guides.rubyonrails.org/routing.html

查看更多
Emotional °昔
6楼-- · 2019-01-21 02:35

Did you want to know how to use POST only? Do this, for example:

resources :items, :only => [:create]

..etc. This is for Rails 3 by the way, and will generate a single resource to POST create. Or if you only need a really small subset of the REST set, just:

match 'items/:id' => "items#create', :via => :post

etc etc.

查看更多
放我归山
7楼-- · 2019-01-21 02:45

Like Don Werve said, take a look at your routes.rb file. In there you probably have something like this:

map.resources :items

This is where rails links the POST and GET requests to certain actions. To see how this works look at the links from the other answers. The docs help a ton.

To all the routes and which actions they link to you can type rake routes into the command prompt when you are in the root of your rails directory. This will show you everything (in terms of routing) that a scaffold gives you.

查看更多
登录 后发表回答