简体   繁体   中英

Dynamic path helpers rails

What are the paths that is automatically added by Rails? Let say you have a Question resource you automatically get questions_path, question_path etc. Where do I see what they resolve to and what I get?

This section might be helpful http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use

Verb    Path              Action     Helper

GET     /photos           index      photos_path
GET     /photos/new       new        new_photo_path
POST    /photos           create     photos_path
GET     /photos/:id       show       photo_path(:id)
GET     /photos/:id/edit  edit       edit_photo_path(:id)
PUT     /photos/:id       update     photo_path(:id)
DELETE  /photos/:id       destroy    photo_path(:id)

If you want to create a helper for show action you can write

photo_path(@photo.id)

where @photo is your model object. Or you can pass @photo directly if it responds to id method.

photo_path(@photo)
edit_photo_path(@photo)

You can also load rails console (in terminal) and test routes using app like so app.photo_path(1) (it will show you the route for the photo with id equals 1 )

Just use:

rake routes

This will list all routes defined. The first column is relevant for you path helpers.

If you have the following in your routes file:

resources :questions

Then Rails provides the following restful routes for you:

GET     /questions          index       list of questions
GET     /questions/new      new         show new question form
POST    /questions          create      create a new question
GET     /questions/:id      show        show a specific question
GET     /questions/:id/edit edit        show form to edit question
PUT     /questions/:id      update      update a specific question
DELETE  /questions/:id      destroy     delete a specific question

You can also run rake:routes to see what is being generated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM