如何在 Rails 中处理多个布局

How to handle multiple layout in Rails

我们在应用程序中有很多面板,如管理员、校长、学生、家长等。

每个面板都有自己的布局 所以在登录后我们使用 WelcomeController

处理这个
class WelcomeController < ApplicationController
  def index
    respond_to do |format|
      format.html do
        return render :home if current_user.nil?
        return render :admin if current_user.super?
        return redirect_to("/student/lesson") if current_user.student?
        return redirect_to("/teacher/lesson") if current_user.teacher?
        return render "layouts/principal" if current_user.principal?
        return render "layouts/coordinator" if current_user.coordinator?
        return render "layouts/viceprincipal" if current_user.viceprincipal?
        return render "layouts/parent" if current_user.parent?
      end
    end
  end
end

所以现在为了从控制器获取数据,我们重定向到他的路由 Like for Student

return redirect_to("/student/lesson") if current_user.student?

但我们希望在 URL / 上从控制器获取数据。 所以我的问题是如何获取数据?所以我们可以在视图中使用

我是 Rails 的新手,如果我使用有误,请告诉我。我会从模型中获取数据吗?

在路线中我们使用

get '/student/lesson', to: 'student_lesson_plan#index', as: 'student_lesson'

并且从索引 Action 中我们有我们使用的变量。所以我想要 而不是

return redirect_to("/student/lesson") if current_user.student? 像这样

return render "layouts/student" if current_user.student?

而且我可以使用我在 student_lesson_plan#index 或从其他地方

初始化的那些变量

在我的应用程序中,我会设置类似这样的内容以根据条件获得不同的布局:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  layout :layout_by_user_types # works like a before action 

  def layout_by_user_types
    if current_user.student?
      "students/application"
    elsif current_user.other_condition?
      "other_name_space/application" 
    else
      "application"
    end
  end

end

在我的视图文件夹中,我会将不同的布局分开,这样我可以根据需要调用不同的 css/js ...

-views
  -layouts
    -students
      -_my_partials.html.erb
      -application.html.erb
    -other_users
      -_my_partials.html.erb
      -application.html.erb
....

对我们如何通过控制器从模型获取信息到视图的基本理解:

在控制器中

class StudentController < ApplicationController

  def_index
   @my_var_i_want_in_my_view = Student.my_query_to_database
   @my_var_i_want_in_my_view_too = Student.my_super_action_that_will_give_some_data_and_that_is_a_method_in_my_model
  end

end

然后在视图中你可以抓取并使用@my_var_i_want_in_my_view