Rails username in url

Trying to use username in my rails routes.

Routes that work:

resources :users, only: [:show, :create, :update, :destroy] get "/:username" => "users#show", as: :user get "/:username/account" => "users#account", as: :user_account get "/:username/interests", to: "users#interests", as: :user_interests get "/:username/offers" => "users#offers", as: :user_offers get "/:username/trades" => "users#trades", as: :user_trades 

but now a route like:

 get "/signup" 

matches the rule /:username

I know that I can reorder my routes so that / registration appears earlier, but it seems a bit hacked.

Is there any way to rewrite this? Or is this the only way to have a reserved username check?

thanks

EDIT

In the end, I added a user model confirmation with reserved words. Namespacing is a good idea, but I don't want to pollute my URLs.

For the record, the Twitter namespace instead of names such as: twitter.com/i/discover (goes to Twitter) twitter.com/discover (goes to @discover profile)

Names of backup objects, such as "search", as far as I can tell

I followed Pinterest approach with code:

checks:

 validate :reserved_username private def reserved_username reserved_usernames = %w[index show create destroy edit update signup interests interest item items search offers offer community about terms privacy admin map authentication] errors.add(:reserved_username, "username is reserved for the app") if reserved_usernames.include?(username) end 
+4
source share
1 answer

Routes take precedence in the order of definition, with earlier redefinition later. If you want your /signup path to work, you need to define it before /:username . These are not hacks, this is just how it works.

You can exclude certain matches for :username , but this slows down your routing if the list becomes long, or you have to rewrite it as a regular expression, which is probably the hack definition here.

When you create root paths for arbitrary user names, you should consider creating a prefix for all your other routes so that they do not conflict. For example, /=/signup or /-/signup . You can also use something like /_signup if you have /_signup underscores at the beginning of usernames or some other way of defining an exception that you can use to assign all of your other routes.

This way, you don’t have to worry about checking the user database before introducing a new function or creating a long, exhaustive list of invalid names.

+7
source

Source: https://habr.com/ru/post/1483192/


All Articles