如何从 rails 3 中的模型获取实际的 HTTP 请求? [英] How to get the actual HTTP request from a model in rails 3?

查看:25
本文介绍了如何从 rails 3 中的模型获取实际的 HTTP 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 rails 3 中的模型获取实际请求.我知道并不总是处理请求,但如果有请求,我希望能够访问它.怎么可能达到.在控制器的情况下,请求方法就位.但是现在我需要从较低级别"访问请求.你能告诉我如何在 Rails 中做到这一点吗?

I would need to get the actual Request from a model in rails 3. I know there is not always an request processed, but if there is one I would like to be able to access it. How is it possible to reach. In case of controllers, the request method is in place. But now I need to access the request from a bit "lower level". Can you give me any clues how to do it in Rails?

推荐答案

您可以将请求存储在线程中,然后在任何地方访问它.这绝对是一种黑客行为,因为您真的不应该以这种方式破坏 MVC 约定,并且如果模型确实依赖于请求,您始终可以将请求作为参数传递给模型.

You can store the request in the thread, and then access it anywhere. This is def a hack as you really should not break the MVC convention this way, and if a model is really request dependent you could always pass the request to the model as a parameter.

但是让你的请求随处可用的技巧是 application_controller.rb:

but the hack to make your request available everywhere would be for application_controller.rb:

before_filter :store_request_in_thread

def store_request_in_thread
  Thread.current[:request] = request
end

并且在您的模型 somemodel.rb 或您希望请求已经存在的任何地方,您只需访问该请求:

and in your model somemodel.rb or really anywhere you expect request to already exist, you can just access the request:

def something
  request = Thread.current[:request]
end

这篇关于如何从 rails 3 中的模型获取实际的 HTTP 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆