Ruby on rails routing username matching

I am sure there is a simple solution, but I can not find it.

I want to map the following dynamic username:

/users/dymanicUsername 

How it would look in route.rb

Thanks for any help.

+2
source share
2 answers

Allister

To do this, simply override to_param in your model. For instance:

 #users.rb def to_param self.username end 

You will soon encounter some problems:

  • Conflicts with existing routes. For example, the username should not be "new", did it work?
  • to select a user in the controller, you must create a method (what I did mayybe is not the best solution) in your model, for example, self.find_for_controller (username)
  • your username should only contain characters with URL support (forget accents, conjunctions, etc.). The solution for this is to have a second attribute name username_urlized , which, of course, must be unique and not contradict other routes.

And maybe more problems :)

Also, if you want something like twitter (yoursite.com/dynamicUserName), follow these steps in routes.rb:

 resources :users, :path=>'' do 
+5
source

Here is a good explanation from 2006 that works great for Rails 2.3. *: http://garrickvanburen.com/archive/using-names-in-rails-routes-instead-of-ids

The main problems that I see are that you would like to provide not only all of the above, which Marcel mentions, but the name is unique. those. put the index in the name with :unique => true in the hyphen.

For rails3, which I’m only updating to now, you will have to route differently. For example, map.connect is replaced by match .

+1
source

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


All Articles