Confirm on Apache Passenger deployment: rails access session in model

后端 未结 2 1733
醉酒成梦
醉酒成梦 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.

    0 讨论(0)
  • 2020-12-30 12:44

    Yes. It is the only efficient way I found to use session data in model. I also used it and never faced any deployment issue with Apache + passenger.

    But you need to confirm when you will be playing with session values. On each new request to server, session value gets stored in thread and we can access it in model. If you are applying any logic by using thread value, then also make sure with situation when thread value might be nil also.

    Because I got an issue where on development, my every code worked fine but on production, during starting server it caused an issue as initially it considered thread value as nil.

    0 讨论(0)
提交回复
热议问题