使用HTTP put时,Rails会话为空

Cam*_*Cam 10 ajax session ruby-on-rails ruby-on-rails-3

我有一种情况,一个特定的链接导致一个空的会话哈希.这不好,因为我需要使用session_id来查找模型.

导致问题的链接是:

<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>
Run Code Online (Sandbox Code Playgroud)

以及从会话ID中找到模型的代码(使用before_filter调用):

def get_organisation
  @organisation = Organisation.find_by_session_id(session[:session_id])
end
Run Code Online (Sandbox Code Playgroud)

在调试器模式下,session=={}

如果我将link_to更改为HTTP"get"而不是"put",则会发送会话.但是,此请求不适合'get',因为它正在修改数据.

为什么"得到"包括会话,但"放"不是?

Cam*_*Cam 10

好的,找到了.由于链接是http-put,因此rails不会自动包含真实性令牌,就像使用http-get一样.因此,通过将真实性令牌作为参数传递,rails会识别会话.

<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>
Run Code Online (Sandbox Code Playgroud)

这个页面帮助我找到了解决这个问题的方法:http://www.kolodvor.net/2010/01/02/rails-csrf-and-ajax-requests/