Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails session is blank when using HTTP put

I have a situation, where one particular link is resulting in an empty session hash. This is not good as I need to find a model by using the session_id.

The link that is causing trouble is:

<div id="marker_images">
  <% @marker_image_urls.each do |image_url| %>
    <%= link_to( image_url, 
                 location_type_path(@location_type.id, 
                 :location_type => {:preset_marker_url => image_url}), 
                 :method => :put,
                 :remote => true ) %>
  <% end %>
</div>

and the code that finds the model from the session id (which is called using a before_filter):

def get_organisation
  @organisation = Organisation.find_by_session_id(session[:session_id])
end

In debugger mode, session == {}

If I change the link_to to be a HTTP 'get' instead of 'put', the session is sent. However, this request isn't appropriate for a 'get' as it is modifying data.

Why would 'get' include the session, but 'put' not?

like image 621
Cam Avatar asked Mar 09 '11 04:03

Cam


2 Answers

Ok, found it. Because the link is a http-put, rails does not automatically include the authenticity token, as it does with an http-get. So, by passing the authenticity token as a param, rails recognises the session.

<div id="marker_images">
  <% @marker_image_urls.each do |image_url| %>
    <%= link_to( image_tag(image_url), 
                 location_type_path(@location_type.id, 
                                    :location_type => {:preset_marker_url => image_url},
                                    :authenticity_token => form_authenticity_token), 
                 :method => :put,
                 :remote => true ) %>
  <% end %>
</div>

This page helped me out in stumbling upon this solution: http://www.kolodvor.net/2010/01/02/rails-csrf-and-ajax-requests/

like image 85
Cam Avatar answered Sep 28 '22 04:09

Cam


It happens if you forgot to add <%= csrf_meta_tags %> to your layout. Add it like

<head>
  <%= csrf_meta_tags %>
</head>
like image 39
Vikrant Chaudhary Avatar answered Sep 28 '22 06:09

Vikrant Chaudhary