0

Users of my app are now able to access their profile (users/show.html.erb) like so:

domain.com/johndoe

To make that happen, I used the following code

routes.rb:

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

user.rb:

extend FriendlyId
friendly_id :username, use: [:finders]
validates_uniqueness_of :username

users_controller.rb:

def show
    @user = User.friendly.find(params[:friendly_id])
end

The problem is my other routes such as domain.com/explore and domain.com/admin no longer work since the router thinks they are usernames. Just to clarify, "explore" and "admin" are not user profiles but models of their own.

Now it throws an error like this:

can't find record with friendly id: "explore"

How can I solve this problem?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Joshua
  • 73
  • 2
  • 8

2 Answers2

1

There are two parts to this solution. In the immediate term, you want to restore functionality to your site, and ensure that users can't override other routes.

  1. Move your friendly_id route to the bottom of your routes.rb file, below all the other "explore" and "admin" routes. Since routes are parsed from top to bottom, this allows your main routes to take precedence.

  2. Secondly, you'll want to look in FriendlyId's reserved words, to stop users from creating slugs that would leave them unable to access their account. More info here too.

Community
  • 1
  • 1
gwcodes
  • 5,632
  • 1
  • 11
  • 20
0

You could try and add the words you'd want to skip in the config/initializers/friendly_id.rb in the config.reserved_words array:

config.reserved_words = %w(new edit .... explore admin)

And restart the server.

bishal
  • 676
  • 7
  • 12