Devise: Resource specific Logic in Rails Routes : Examples

If you are willing to implement or learn how to route a particular URL request to specific controller on the basis of which role the currently logged-in user is.

# in routes.rb
authenticate :user, -> (user) { user.stylist? } do
  resources :stylist_profiles, only: [:index, :show], path: '/profile'
end

authenticate :user, -> (user) { user.customer? } do
  resources :customer_profiles, only: [:index, :show], path: '/profile'
end

The URL /profile or /profile/1 will route to StylistProfileController if user’s role is Stylist and will route to CustomerProfileController if user’s role is Customer .


condition = -> (u) {
  ['qa', 'development', 'staging'].include?(Rails.env) || (u.admin? && Rails.env.production?)
}

authenticate :user, condition do
  mount Sidekiq::Web => '/sidekiq'
  mount RedisBrowser::Web => '/redis-browser'
end

Some additional examples

# in config/routes.rb
# Home page is root for UnAuthenticated visitors
#  This shall be at the top
unauthenticated :user do
  root 'pages#home', page: 'home'
end

authenticate :user, ->(user) {user.vehicle_owner? } do
  root 'vehicle_owners/quote_requests#index'
end

authenticate :user, ->(user) {user.garage_owner? } do
  root 'garage_owners/quote_requests#index'
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s