我正在使用它来访问会话 模型 </跨度> 。
http://www.zorched.net/2007/05/29/making-session-data-available-to-models-in-ruby-on-rails/
任何人都可以确认它可以与Apache + Passenger一起使用 部署 </跨度> 太?
或者,如果有任何其他替代方案可以实现相同的目标?
谢谢,
伊姆兰
我没有在互联网上找到任何有效的代码,所以我做了一些研究并写了自己的代码。它适用于Rails 3.2.x,也可能适用于其他一些版本。
将其插入您的 ApplicationController
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
我不会提醒您从模型访问会话可能会导致代码错误。 其他帖子可能会告诉你,你是愚蠢的 。虽然有一些正当理由可以从您的模型访问会话,例如实现 Model.save 方法,保存到当前用户会话。
Model.save
是。这是我在模型中使用会话数据的唯一有效方法。我也使用它,从未遇到过Apache +乘客的任何部署问题。
但您需要确认何时使用会话值。在每个对服务器的新请求中,会话值存储在线程中,我们可以在模型中访问它。如果您通过使用线程值应用任何逻辑,那么还要确保线程值也可能为零的情况。
因为我在开发时遇到了一个问题,我的每个代码都运行良好,但在生产时,在启动服务器时它引起了一个问题,因为最初它将线程值视为零。