SessionsHelper in railstutorial.org: Should helpers be general-purpose modules for code not needed in views?

前端 未结 4 1627
失恋的感觉
失恋的感觉 2020-12-14 19:13

railstutorial.org has a suggestion which strikes me as a little odd.

It suggests this code:

class ApplicationController < ActionController::Base         


        
4条回答
  •  借酒劲吻你
    2020-12-14 19:49

    FWIW, I store the current user in the User class:

    class User < ActiveRecord::Base
      cattr_accessor :current
      ...
    end
    

    This can be referenced in all 3 MVC tiers; it is set in the controller like so (and likewise on login, of course):

    def set_current_user
      User.current = (session[:user_id]) ? User.find_by_id(session[:user_id]) : nil
    end
    

    Among other things, this allows me to have audit logs at the ActiveRecord level that capture the current user (when applicable).

提交回复
热议问题