Rails, Devise: Same resource, different controller based on user type

人盡茶涼 提交于 2019-12-06 14:06:15

It turns out the best way to achieve that is to use routing constraints as such:

# config/routes.rb

resources :products, module: 'customers', constraints: CustomersConstraint.new
resources :products, module: 'admins', constraints: AdminsConstraint.new


# app/helpers/customers_constraint.rb

class CustomersConstraint
  def matches? request
    !!request.env["warden"].user(:customer)
  end
end


# app/helpers/admins_constraint.rb

class AdminsConstraint
  def matches? request
    !!request.env["warden"].user(:admin)
  end
end

I stored the constraint objects in the helper folder because I don't really know the best place to put them.

Thanks to @crackofdusk for the tip.

For this you will need to override the existing after_sign_in_path_for method of devise. Put this in your app/controllers/application_controller.rb

def after_sign_in_path_for(resource)

      if resource.class == Admin   

          '/your/path/for/admins'

      elsif resource.class == Customer

        '/your/path/for/customers'

      end 
end

Note: If you want to implement previous_url that was requested by user then you can use it like this:

  session[:previous_url] || 'your/path/for/admins'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!