如何在Rails模型中获取request.uri?

$request = request 

当我在控制器中写这个时,它会工作。 但如果我需要在模型或应用程序控制器中使用此变量,我该怎么办?

模型存在于Web请求的上下文之外。 您可以在irb中实例化它们,您可以在延迟的作业或脚本等中实例化它们。如果模型依赖于请求对象,则这些都不可能。

正如tsdbrown所说,你必须以某种方式从使用该模型的上下文中传递该信息。

我知道了

 class ApplicationController < ActionController::Base protect_from_forgery before_filter :beforeFilter def beforeFilter $request = request end end 

现在我们可以在代码中的任何地方使用$ request全局变量

您无权访问模型中的请求对象,您必须传递request.request_uri。

也许通过自定义方法。 例如@object.custom_method_call(params, request.request_uri)

另一种选择是在模型中添加attr_accessor :request_uri并在其中设置/传递:

 @object.update_attributes(params.merge(:request_uri => request.request_uri)) 

你需要做一个黑客来获取模型中的request.uri。 这是不推荐的。 您应该将其作为模型中定义的方法中的参数传递。

如果你使用rails> 5.0,你可以在下面做

在模型/关注中添加一个模块

 module Current thread_mattr_accessor :actor end 

在applicaton_controller做

 around_action :set_thread_current_actor private def set_thread_current_actor Current.actor = current_user yield ensure # to address the thread variable leak issues in Puma/Thin webserver Current.actor = nil end 

然后在线程中的任何地方获取current_user

 Current.actor 

对于Rails 5,您需要使用before_action