Open Override ID Param
How to Override the Named Route Parameter ID
In the previous posts, we've learned about the concepts of dynamic segments as well as named routes in Rails. Naming a route generates two helper methods which can be used to generate the route URL, whereas a dynamic segment allows us to create dynamic routes, where the parts of the URL can vary.
In this post, we'll combine these two concepts. Consider the following named route which contains a dynamic segment called :id
:
# config/routes.rb
get "item/:id", to: "items#show", as: "item"
When the application receives a request on /item/4
, it forwards it to the ItemsController#show
action. You can access the ID of the post as follows: params[:id]
.
To generate the item URL, you can use the named route helper methods item_path
and item_url
, passing the ID of the post.
item_path(id: @item.id) # /item/10
In this example, @item
is an instance of a Rails model.
Typically, most of the time you'll work wi