Rajdeep Singh
Rajdeep Singh

Reputation: 17834

What is the use of request.referer?

I want to know what the following code does. What is the use of request.referer?

@board = request.referer['dashboard'] if request.referer

Upvotes: 8

Views: 21157

Answers (2)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

request.referer gives you the previous URL or / if none. It is usually used to redirect the user back to the previous page (link)

More information here

Regarding your question, it is simply returning 'dashboard' if found in request.referer. Look at the following example:

> str = "hello world!"
 => "hello world!"
> str['hello']
 => "hello"
> str['lo wo']
 => "lo wo"
> str['foo']
 => nil

However, you should not depend on this method to redirect your user back. You can do this in your controller instead:

redirect_to :back

Upvotes: 14

Rajarshi Das
Rajarshi Das

Reputation: 12320

request.referer gives you the previous URL or / if none

In library you can see:

def referer    
  @env['HTTP_REFERER'] || '/'
end

You can use the referer technique for this, but you'll have to capture it when entering the form instead of when the form is submitted. Something like this:

<%= hidden_field_tag :referer, (params[:referer] || request.env['HTTP_REFERER']) %>

Then you can use params[:referer] in the controller to redirect back.

Upvotes: 1

Related Questions