You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ruby on Rails的Rodauth中获取当前登录用户并判断其类型?

用Rodauth获取当前登录用户类型并展示对应页面的方法
  • 获取当前登录用户实例
    Rodauth默认提供rodauth.current_account方法来获取当前登录的用户(默认用户模型为Account)。如果在Rails项目中,你可以通过配置把这个方法设为控制器和视图可用的helper:

    # config/initializers/rodauth.rb
    Rodauth::Rails.configure do
      enable :login
      helper_method :current_account # 让current_account在控制器、视图中直接调用
    end
    

    若你的用户模型不是默认的Account(比如是User),需要在配置中指定模型名,并调整helper方法:

    Rodauth::Rails.configure do
      enable :login
      account_model :user
      helper_method :current_user
    end
    
  • 根据用户类型展示不同页面
    假设你的用户表中有区分类型的字段(比如type、role),拿到用户实例后直接访问该字段即可判断类型,进而渲染对应页面:
    控制器示例:

    def dashboard
      case current_account.type
      when "Admin"
        render "admin_dashboard"
      when "Merchant"
        render "merchant_panel"
      when "Customer"
        render "customer_home"
      else
        render "default_dashboard"
      end
    end
    

    视图示例:

    <% if current_account.role == "editor" %>
      <div class="editor-actions">
        <%= link_to "发布新文章", new_article_path %>
        <%= link_to "审核文章", pending_articles_path %>
      </div>
    <% else %>
      <div class="user-actions">
        <%= link_to "我的收藏", favorites_path %>
        <%= link_to "修改资料", edit_user_path(current_account) %>
      </div>
    <% end %>
    

内容的提问来源于stack exchange,提问作者Michael Zhang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 13:40:59