Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the actual HTTP request from a model in rails 3?

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?

like image 585
fifigyuri Avatar asked Mar 04 '11 17:03

fifigyuri


People also ask

What is the best way to get the current request URL in Rails?

You should use request. original_url to get the current URL.

What do models do in Rails?

Models are used to represent data from the database (rows of data). The hash representing a row of data can be used to read and update that row's associated data.


1 Answers

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.

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

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
like image 87
Kalendae Avatar answered Sep 20 '22 23:09

Kalendae