确认Apache Passenger部署:rails访问模型中的会话

我正在使用它来访问Model中的会话。

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

任何人都可以确认它也适用于Apache + Passenger部署吗?

或者,如果有任何其他替代方案可以实现相同的目标?

谢谢,

伊姆兰

是。 这是我发现在模型中使用会话数据的唯一有效方法。 我也使用它,并且从未遇到过Apache +乘客的任何部署问题。

但您需要确认何时使用会话值。 在每个对服务器的新请求中,会话值存储在线程中,我们可以在模型中访问它。 如果您通过使用线程值应用任何逻辑,那么还要确保线程值也可能为零的情况。

因为我在开发时遇到了问题,我的每个代码都运行良好,但在生产时,在启动服务器时它引起了一个问题,因为最初它将线程值视为零。

我没有在互联网上找到任何有效的代码,所以我做了一些研究并写了自己的代码。 它适用于Rails 3.2.x,也可能适用于其他一些版本。

将其插入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 

我不会提醒您从模型访问会话可能会导致代码错误。 其他post可能会告诉你,你是愚蠢的 。 虽然从模型中访问会话有一些正当理由,例如实现Model.save方法,但是会保存到当前用户会话。