Note that there are some explanatory texts on larger screens.

plurals
  1. PORails custom route for user profile
    primarykey
    data
    text
    <p>I want to have the URL of a users profile in this format: mydomain.com/username</p> <p>I have started to implement it in the user model:</p> <p>user.rb</p> <pre><code>before_create :create_permalink . . def to_param permalink end . . private def create_permalink self.permalink = username.downcase end </code></pre> <p>users_controller.rb</p> <pre><code>def show @user = User.find_by_permalink(params[:permalink]) end </code></pre> <p>routes.rb</p> <pre><code>match "/:permalink", to: "users#show", via: 'get' </code></pre> <p>When I visit mydomain.com/username a user profile does display but when I do it through the <code>user_path(current_user)</code> link, I get this error </p> <pre><code>undefined method `username' for nil:NilClass </code></pre> <p>and the URL is mydomain.com/user/username, which I don't want.</p> <p>How do I edit the default rails route and edit user route to be in the format I want?</p> <p>routes.rb:</p> <pre><code>Code::Application.routes.draw do resources :users, except: [:edit, :show] resources :sessions, only: [:new, :create, :destroy] root 'pages#home' match '/help', to: 'pages#help', via: 'get' match '/about', to: 'pages#about', via: 'get' match '/contact', to: 'pages#contact', via: 'get' match '/signup', to: 'users#new', via: 'get' match '/signin', to: 'sessions#new', via: 'get' match '/signout', to: 'sessions#destroy', via: 'delete' get '/:permalink', to: 'users#show', as: 'user' get '/:permalink/edit', to: 'users#edit', as: 'edit_user' end </code></pre> <p>After removing just the <code>as: 'user'</code> line and left <code>as: 'edit_user'</code> I ran <code>bundle exec rake routes | grep -i "user"</code>:</p> <pre><code> users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format) users#new user PATCH /users/:id(.:format) users#update PUT /users/:id(.:format) users#update DELETE /users/:id(.:format) users#destroy signup GET /signup(.:format) users#new GET /:permalink(.:format) users#show edit_user GET /:permalink/edit(.:format) users#edit </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload