如何在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
相关产品推荐
相关产品推荐

