自定义重定向基于rails 5中的用户角色和设计

时间:2018-04-01 17:10:33

标签: ruby-on-rails devise ruby-on-rails-5

自从我使用rails之后已经有一段时间了,我正在为我工​​作的公司跳进一个“项目”..

基本上我要做的是在登录时将登录到应用程序的用户重定向到特定页面。

例如,管理员用户将被重定向到管理仪表板,所有者将被重定向到所有者仪表板,驱动程序将被重定向到驱动程序仪表板。

我过去使用单个视图完成此操作,然后使用elseif语句填充它。但我发现,为了让我的代码看起来很笨拙而且减慢了应用程序的速度。

我似乎无法找到任何文档(可能是因为我已经离开游戏这么久)关于如何根据用户角色重定向到特定网址。这甚至可能吗?如果有的话,有人会愿意分享一些资源,因为我在这个部门真的很挣扎。

提前致谢!

编辑1:实施ApplicationController方法以查找用户角色并重定向到适当的页面。

所以我在ApplicationController

中添加了几行代码
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

def after_sign_in_path_for(resource)
  if current_user.role == "dispatch"
    dashboard_dispatch_path
  else
    root_path
  end
end

end

当我尝试加载页面时,浏览器中的网址会更改为正确的网址,但是我收到以下错误:

Better Errors screenshot

来自rails服务器的堆栈跟踪:

Started POST "/users/sign_in" for 127.0.0.1 at 2018-04-01 12:10:58 -0600
Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"LJSAbgb3spFs0kEgFMYa40m2TZmZvH7weq53ciuGZAO07SUBgTHdxYTH0+MjRuYZIi+9++zIjnJP2rllVws5DA==", "user"=>{"email"=>"swixxxx@xxxxxltd.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
  User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["email", "swixxxx@xxxxxxltd.com"], ["LIMIT", 1]]
   (0.2ms)  BEGIN
  SQL (0.6ms)  UPDATE "users" SET "current_sign_in_at" = $1, "sign_in_count" = $2, "updated_at" = $3 WHERE "users"."id" = $4  [["current_sign_in_at", "2018-04-01 18:10:58.835548"], ["sign_in_count", 2], ["updated_at", "2018-04-01 18:10:58.836544"], ["id", 2]]
   (1.0ms)  COMMIT
Redirected to http://localhost:3000/dashboard/dispatch
Completed 302 Found in 150ms (ActiveRecord: 2.6ms)


Started GET "/dashboard/dispatch" for 127.0.0.1 at 2018-04-01 12:10:58 -0600

ArgumentError - wrong number of arguments (given 3, expected 0):
  app/controllers/dashboard_controller.rb:5:in `dispatch'

Started POST "/__better_errors/cda7f553a5c61c4b/variables" for 127.0.0.1 at 2018-04-01 12:10:58 -0600

编辑2:添加控制器代码:

class DashboardController < ApplicationController

  def admin
  end

  def dispatch
  end

  def owner
  end

  def driver
  end

  def client
  end

  def guest
  end

end

0 个答案:

没有答案