Ruby on rails Rails:基于不同角色的不同布局

Ruby on rails Rails:基于不同角色的不同布局,ruby-on-rails,Ruby On Rails,我的应用程序中有3个不同的角色:来宾、用户和管理员。根据查看页面的角色,某些页面需要具有不同的布局。我想知道是否有比我现在做的更简单的方法 例如,我目前有3种不同的布局。在我的VenuesController中,我有3种不同的操作。但在我看来,应该有一个更简单的方法 def index @venues = Venue.paginate(page: params[:page]).order("name ASC") end def admin_index @venues = Venue.p

我的应用程序中有3个不同的角色:来宾、用户和管理员。根据查看页面的角色,某些页面需要具有不同的布局。我想知道是否有比我现在做的更简单的方法

例如,我目前有3种不同的布局。在我的VenuesController中,我有3种不同的操作。但在我看来,应该有一个更简单的方法

def index
  @venues = Venue.paginate(page: params[:page]).order("name ASC")
end

def admin_index
  @venues = Venue.paginate(page: params[:page]).order("name ASC")
  render layout: "admin"
end

def user_index
  @venues = Venue.paginate(page: params[:page]).order("name ASC")
  render layout: "user"
end

我想我可以有一个
索引
操作,然后在其中测试当前用户的角色是什么?

使用以角色命名的布局文件就可以了

def index
  @venues = Venue.paginate(page: params[:page]).order("name ASC")
  # substitute your favorite current_user check and role name method
  render layout: current_user.present? ? current_user.role.name : 'application'
  # app/views/layouts/admin.html.erb
  # app/views/layouts/user.html.erb
  # app/views/layouts/application.html.erb
end
请注意,根据这些版面之间的实际差异(或不差异),在单个版面中使用助手等工具来确定可见内容可能更简单、更易于维护。您还可以使用角色名称的部分,或将这些技巧中的任何一种切分到对您有意义的程度。

使用以下方法:

class HomeController < ApplicationController
  before_action :get_women_category, :get_men_category
  def index
  end

  private

  def resolve_layout
    if current_user && current_user.has_role?(:super_admin)
       'superadmin'
    elsif current_user && current_user.has_role?(:company_admin)
       'application'
    else
      'application'
    end
  end

end