代码之家  ›  专栏  ›  技术社区  ›  RubyRedGrapefruit

有没有一种Rails模式可以为不同类型的用户提供不同的主页?

  •  0
  • RubyRedGrapefruit  · 技术社区  · 3 年前

    我最初的想法是 home_page 上的属性 User 建模,然后做 redirect_to 在验证之后。是这么简单,还是有更好的方法?

    作为背景,以下是一些用例:

    一个用户可以是管理员,并且可以出于支持目的模拟网站上的其他用户。我们的管理员这样做是为了“看到”客户看到的内容。登录时,管理员将被引导到一个页面,该页面显示当前使用情况统计信息以及整个应用程序中发生的任何错误。

    另一种类型的用户是来自合作伙伴市场的合作者。比方说,这家公司名为Amazing。Amazing的经理可以登录并查看Amazing市场上销售产品的所有用户,但他没有管理员的权限。我想将这个用户重定向到一个页面,显示Amazing市场上的所有卖家。

    标准客户将被引导到一个仪表板页面,该页面将帮助他们管理市场上的广告。

    0 回复  |  直到 3 年前
        1
  •  1
  •   Vi.    3 年前

    如果使用 Devise 。在一个旧项目上,我做了这样的事情,代码不是很干净,但你可以得到一个想法:

    路线.rb

    Rails.application.routes.draw do
      mount Ckeditor::Engine => '/ckeditor'
    
      devise_for :admins,
                 :frontend_operators,
                 :backend_operators,
                 class_name: 'User',
                 path: '',
                 controllers: {sessions: 'frontend/auth/sessions',
                               confirmations: 'frontend/auth/confirmations',
                               unlocks: 'frontend/auth/unlocks',
                               passwords: 'frontend/auth/passwords',
                               registrations: 'frontend/auth/registrations'},
                 path_names: {sign_in: 'login',
                              sign_out: 'logout',
                              password: 'secret',
                              confirmation: 'verification',
                              sign_up: 'register',
                              edit: 'profile/edit'}
    ...
    
      authenticated :backend_operator do
        get :backend_operator_root, action: :index, controller: "backend/home"
      end
      authenticated :frontend_operator do
        get :frontend_operator_root, action: :index, controller: "frontend/home"
      end
      authenticated :admin do
        get :admin_root, action: :index, controller: "backend/home"
      end
    end
    

    application_controller.rb

    class ApplicationController < ActionController::Base
    
      devise_group :user, contains: [:backend_operator, :frontend_operator, :admin]
    
      [:backend_operator, :frontend_operator, :admin].each do |model|
    
        define_method("decorated_current_#{model}") { send("current_#{model}").decorate }
        helper_method "decorated_current_#{model}".to_sym
      end
    
      before_action :set_root, unless: :root_present?
    
      protected
    
      def set_root
        Rails.application.config.root_url = root_url
      end
    end