I am developing my first application in rails. I went through the Rails Routing from the Outside In
documentation but unable to figure out how to setup the following route.
I have a ClientsController and the for the show action I want to display the client's first and last name with spaces replaced with hyphens, in the url.
Instead of the following
the link should be (first name : john, last name : doe)
The strategy here is to treat the name in the URL like a throw-away variable, since it's not being used as an identifier. Notice that in StackOverflow you can type any name you want, and as long as the id is correct you'll get the page you want. So we can do that too:
resources :clientsso you can go to
get 'clients/:id/:name', to: 'clients#show', as: :client_name. This lets you go to
/clients/1/anything-you-wantand it will hit the
id: 1and `name: "whatever-you-want".
User#url_name, but it might make more sense to define
url_name(client)in a helper since it's not really relevant to the model.
client_name_path(@client.id, @client.url_name); e.g.,
client_name_path(1, "john-doe"). This url-helper name is defined by our choice to use
as: :client_namein the route. The return value of this call should be "/clients/1/john-doe", which we have already routed to the
So far, links in your app will have the correct URL, but a user could still type in any name in the URL and it would persist in the address bar (even though the page would be fine). If you want to go further like StackOverflow and actually change the url to the correct name you might try in
redirect_to client_name_path(@client.id, @client.url_name) if params[:name] != @client.url_name. Just be careful with that to not get yourself into an infinite loop.