Confirm on Apache Passenger deployment: rails access session in model

后端 未结 2 1819
醉酒成梦
醉酒成梦 2020-12-30 12:25

I am using this to access session in Model.

http://www.zorched.net/2007/05/29/making-session-data-available-to-models-in-ruby-on-rails/

Can anybody confirm

2条回答
  •  渐次进展
    2020-12-30 12:28

    I did not find any code on the internet that works, so I did some research and wrote my own. It works for Rails 3.2.x and probably on some other versions.

    Insert this in your ApplicationController

      # Set a filter that is invoked on every request
      before_filter :_set_current_session
    
      protected
      def _set_current_session
        # Define an accessor. The session is always in the current controller
        # instance in @_request.session. So we need a way to access this in
        # our model
        accessor = instance_variable_get(:@_request)
    
        # This defines a method session in ActiveRecord::Base. If your model
        # inherits from another Base Class (when using MongoMapper or similar),
        # insert the class here.
        ActiveRecord::Base.send(:define_method, "session", proc {accessor.session})
      end
    

    I will not remind you that accessing your session from a model may lead to bad code. Other posts may tell you, that you are stupid. Though there are some valid reasons to access the session from your model, like implementing a Model.save method, that saves to the current users session.

提交回复
热议问题