Joe Morano
Joe Morano

Reputation: 1895

Is it possible to set a url to ":name" instead of "models/:id"?

I have a model "User", which has a :name attribute. Right now, the User "show" action is defined by the following route:

get '/users/:id', to: 'users#show', as: 'user'

This means that the "show" view for a User with id: 4 and name: Joe would be under localhost:3000/users/4.

Is there a way I could get Joe's "show" url to be localhost:3000/joe, and do the same for every user? Every :name is unique.

Upvotes: 0

Views: 34

Answers (1)

Andrew Bryant
Andrew Bryant

Reputation: 529

If I'm reading your question correctly, do you mean this:

get '/:name', to: 'users#show', as: 'user'

That should capture the :name attribute from the URL at the root level, but still go to the same controller.

Here's a link to the Rails Routing guide that I believe covers this (albeit not in too much detail): Rails Routing: dynamic segments

Then to extract the :name attribute instead of the :id attribute change the code in the controller from User.find(params[:id]) to User.find_by(name: params[:name])

Rails Models - find_by method

Upvotes: 2

Related Questions