Ruby-on-rails 如何在 Rails 模型中获取 request.uri?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6307138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:22:03  来源:igfitidea点击:

How do i get request.uri in model in Rails?

ruby-on-railsrubyruby-on-rails-3

提问by Sreeraj

$request = request

When I write this in controller, it will work. But if i need this variable in Model or Application controller, How can i ?

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

回答by DGM

Models exist outside the context of a web request. You can instantiate them in irb, you can instantiate them in a delayed job, or a script, etc. If the model depended on the request object, none of these things would be possible.

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

As tsdbrown says, you have to somehow pass in that information from the context that uses the model.

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

回答by Sreeraj

I got it

我知道了

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :beforeFilter

  def beforeFilter
     $request = request
  end  
end

Now we can use the $request global variable anywhere in the code

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

回答by tsdbrown

You do not have access to the request object in your models, you will have to pass the request.request_uri in.

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

Perhaps via a custom method. e.g. @object.custom_method_call(params, request.request_uri)

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

Another option would be add an attr_accessor :request_uriin your model and set/pass that in:

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

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

回答by wuyuedefeng

if you use rails > 5.0, you can do below

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

add a module in models/concern

在模型/关注中添加模块

module Current
  thread_mattr_accessor :actor
end

in applicaton_controller do

在应用程序控制器中做

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

then in thread anywhere get current_user

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

Current.actor

回答by William

For Rails 5, you need to use before_actioninstead.

对于 Rails 5,您需要before_action改用。

回答by Manish Puri

you will need to do a hack to get request.uri in the model. which is not recommended. You should pass it as a params in the method which is defined in the model.

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