简体   繁体   中英

Bound Parameters in Ruby on Rails

I've previously asked a question related to this topic as well and with the aid of that question I've found the name of exactly what I wanted: “ bound parameters ”.

I have managed to create a routing like "user/:id/dosomething" by adding a member to the routes.rb . However, this type of URL is not the solution I was looking for.

My question is, how do you provide the 'user/dosomething/:id' to match with action user's dosomething action with id sent as parameter?

Here is the section I've read in order to get the idea:

3.1 Bound Parameters

When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. Two of these symbols are special: :controller maps to the name of a controller in your application, and :action maps to the name of an action within that controller. For example, consider this route:

 get ':controller(/:action(/:id))' 

If an incoming request of /photos/show/1 is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the show action of the PhotosController , and to make the final parameter "1" available as params[:id] . This route will also route the incoming request of /photos to PhotosController#index , since :action and :id are optional parameters, denoted by parentheses.

You can add a custom route:

get 'user/doesomething/:id' => 'users#do_something', :as => 'do_something_user'

This will route HTTP GET requests that match the URL user/dosomething/:id to the UsersController 's do_something action. The :as => 'do_something_user' part names the route, so that you can use do_something_user_path and do_something_user_url helpers to generate the URLs.

For more information on routing, see Rails Routing from the Outside In .

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