Firstly, you'd be better using an enum
in your model. This way, you can assign actual roles to the User.role
attribute (not just integers):
#app/models/user.rb
class User < ActiveRecord::Base
enum role: [:shipper, :shop]
end
This will still keep the integer
in the database, but assign an actual name to the role in ActiveRecord. For example, you'll get user.shipper?
and user.shop?
.
Since I was interested to see a resolution, I looked online and found this.
It explains what I had thought - you'll need to use a constraint to validate the role of the user and redirect accordingly. This way, you can send use a single route helper, and have the user sent to different routes depending on their role.
As per this answer, I'd try something like:
# lib/role_constraint.rb
class RoleConstraint
def initialize(*roles)
@roles = roles
@role = request.env['warden'].user.try(:role)
end
def matches?(request)
params = request.path_parameters
@roles.include?(@role) && @role == params[:role]
end
end
#config/routes.rb
resources :users, path: "", except: :show do
get ":role/:id", action: :show, on: :collection, constraints: RoleConstraint.new([:shipper, :shop])
end
This isn't exactly what I'd want but it should create a single route, which is only accessible by the User with a role either as shipper or shop.