开发者

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

$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 ?


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.


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


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))


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


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.


For Rails 5, you need to use before_action instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜