When you are looking up models from your controller, using anything other than the model id, the code you write starts to look unusual.
# app/controllers/trains_controller.rb
class TrainsController < ApplicationController
def show
@train = Train.find_by(reference: params.fetch(:id))
end
end
Weβre looking up the Train record by its reference using a parameter named id.
To avoid confusion we can tell Rails to name the id parameter to something else that would make more sense to us, for example reference. We achieve this by slightly modifying the routes file.
# config/routes.rb
resources :trains, param: :reference
After adding the param: :reference we can now access the parameter in out controller using params.fetch(:reference) allowing our controller to be more explicit.
# app/controllers/trains_controller.rb
class TrainsController < ApplicationController
def show
@train = Train.find_by(reference: params.fetch(:reference))
end
end
We can now say that weβre looking up the Train record by its reference using a parameter named .reference
The URL pattern has now changed from trains/:id to trains/:reference. This works for nested routes too, Rails adds the appropriate prefix to the parameter trains/:train_reference/timetables.