Home > Mobile >  Passing another attribute to params other than the id
Passing another attribute to params other than the id

Time:05-19

I want to access the username attribute of my User model from params using params[:username].

On my user model, I have

class User < ApplicationRecord
  has_secure_password

  validates :email, presence: true, uniqueness: { case_sensitive: false }
  validates :username, presence: true, uniqueness: { case_sensitive: false }
  validates :password, length: { minimum: 6 }, on: :create

  def to_params
    username
  end
end

While on my config/routes.rb, I have:

Rails.application.routes.draw do
  root "pages#home"

  resources :users, path: "/", except: :index
end

and this does partly what I want.

The routes produced are as follows:

     Prefix Verb   URI Pattern         Controller#Action
       root GET    /                   pages#home
      users POST   /                   users#create
   new_user GET    /new(.:format)      users#new
  edit_user GET    /:id/edit(.:format) users#edit
       user GET    /:id(.:format)      users#show
            PATCH  /:id(.:format)      users#update
            PUT    /:id(.:format)      users#update
            DELETE /:id(.:format)      users#destroy

where the :id part outputs the username of User and so I get a route like /jim when accessing the user's homepage.

What bugs me out is I have to use params[:id] when accessing the username on my controllers. Moreover, when I nest the resources like this:

  resources :users do
    resources :posts
  end

I get a route like /users/:user_id/posts(.:format) where :user_id is the username.

Is there a way I could set this up so my routes would look something like:

     Prefix Verb   URI Pattern                Controller#Action
       root GET    /                          pages#home
      users POST   /                          users#create
   new_user GET    /new(.:format)             users#new
  edit_user GET    /:username/edit(.:format)  users#edit
       user GET    /:username(.:format)       users#show
            PATCH  /:username(.:format)       users#update
            PUT    /:username(.:format)       users#update
            DELETE /:username(.:format)       users#destroy

and when I want to access the username from params, I can write params[:username]?

Thanks!

CodePudding user response:

For more details check rails guides overriding-named-route-parameters

Add route like this

Rails.application.routes.draw do
  root "pages#home"

  resources :users, path: "/", except: :index, param: :username do
     resources :posts
  end
end
  • Related