简体   繁体   中英

Routes and query strings magic in Rails

So, I recently saw this code:

<%= link_to "Index", plays_path(id: 1) %>

1) I did not know that the index path or the plays_path took arguments. The URL doesn't have any named parameters and so I didn't think you could.

2) I read about query strings but the docs aren't great. ActionView UrlHelper

There is no usage of the word query strings. How can you just pass any hash to a path in rails and have the params be available in the following controller? What is going on here?

You're exactly correct. Any parameters you pass in to URL / path helpers (which are not part of a named route, such as :id ) will be available as parameters within your controller.

The Rails Routing Guide talks a bit about parameters and is always a good resource for how to best utilize additional parameters passed through a _url or _path helper.

All of the path helpers take a hash of arguments on the end. They're passed as extra parameters in the query string. For instance: plays_path(id: 1) will (likely) generate /plays?id=1 . You can append a whole mess of them on the end as in user_path(user, active_user: 5, secure: 1, other_thing: 'happy') where user is an instance of User with id 30 , would generate /user/30?active_user=5&secure=1&other_thing=happy . Most of the time these are GET parameters.

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