Rails Routes – Dynamic Controller or Module

I was recently looking for a solution to call the correct controller depending on other data (the user that is being viewed). If the user is an admin, call one controller. If the user is a regular user, call another controller. You could redirect to the correct controllers but it’s not elegant. You could also have the controller (or module) directly in the URL but that does not look pretty.

Since there is no Rails way of doing it (and probably not the best thing to do), here is a possible solution that will probably work:


get 'users/:id', to: 'admin/users#show', constraints: lambda { |request| 
  id = request.fullpath.gsub('/users/','').to_i
  User.find_by_id(id).admin?
}

get 'users/:id', to: 'regular/users#show', constraints: lambda { |request| 
  id = request.fullpath.gsub('/users/','').to_i
  !User.find(id).admin?
}

Thanks to kardeiz for the help. Again, this is just a possible solution that can be revised and improved until someone comes up with a Rails way of doing this.

Leave a Reply