0

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 Answers1

1

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

David Routen
  • 349
  • 4
  • 21
  • I add this gem. Then I add this code in User model: `extend FriendlyId friendly_id :username`. But it still diesn't works. P.S. I use devise gem. – Artyom Gunkin Jun 16 '15 at 09:19
  • 1
    Did you follow the **Rails Quickstart** instructions for installing FriendlyId on their [git page](https://github.com/norman/friendly_id)? There are a few steps you need to take before it will work. What errors are you getting? Here is another valuable video tutorial [GoRails #9](https://gorails.com/episodes/pretty-urls-with-friendly-id) as well. – David Routen Jun 16 '15 at 12:50
  • 1
    Now it works, thank you. The problem was in case-sensitivity. I enter the username in the address bar incorrectly. So, how to remove case-sensitivity? – Artyom Gunkin Jun 17 '15 at 10:41
  • 1
    For case sensitivity, just use downcase on the id param before checking it. `User.friendly.find(params[:id].downcase)` should work. – David Routen Jun 17 '15 at 13:21