User path with username

745 views Asked by At

To show User's profile I used their id. In controller:

@user = User.find(params[:id])

In routes:

get ':id' => 'users#show'

But now I try new way with username:

get ':username' => 'users#show' #route

@user = User.find_by(username: params[:username]) #controller

And when I go to user's profile with /username I see error: undefined method posts. In controller I get user's posts. But now it doesn't works. Please tell me why? And I have one more question. When I go to /users or /posts or something else, my app thinks, that I go to uset's page. How to fix it? And what to do, if user sign up with, for example, username: "users"?

1

There are 1 answers

4
David Routen On BEST ANSWER

Artyom you can use the friendly-id gem if you want to make this process easier on you. Ryan Bates has a Railscast on it as well.

That way you can use strings as ids (i.e. your username) in the url:

http://localhost:3000/articles/hello-world

Let me know if you have any questions,

-Dave