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

后端 未结 6 376
一生所求
一生所求 2021-02-01 07:00
$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 ?

相关标签:
6条回答
  • 2021-02-01 07:10

    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.

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

    0 讨论(0)
  • 2021-02-01 07:15

    For Rails 5, you need to use before_action instead.

    0 讨论(0)
  • 2021-02-01 07:25

    if you use rails > 5.0, you can do below

    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.actor
    
    0 讨论(0)
  • 2021-02-01 07:29

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

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

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

    @object.update_attributes(params.merge(:request_uri => request.request_uri))
    
    0 讨论(0)
  • 2021-02-01 07:29

    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.

    0 讨论(0)
  • 2021-02-01 07:34

    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

    0 讨论(0)
提交回复
热议问题