Wednesday, July 08, 2009

authenticity_token not available in Rails 2.X version for non forms

This problem occur  if view is not having any form ...
When a form is being generated rails automatically adds something like
this:
< input name="authenticity_token" type="hidden" value="11ff3908e6cd4be7b4041a93b783829ce6b12349" >  
If view does not contain form ("authenticity_token")  InvalidAuthenticityToken is being raised.
 
So You can do something like this in your view to make your authenticity 
token available to your javascript in your views.

<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>

That will make your authenticity token available to your custom 
javascript Ajax requests.  If you're using prototype.js and you want to 
do a custom PUT, you do something like this.

  new Ajax.Request ('/products/1', {
    method: 'put',
    parameters: 'product[name]=chair&authenticity_token=' + 
window._token});
 
If you use Jquery :=
$.ajax({
              url: "people/1,
              global: false,
              type: "PUT",
              data: ({'person[name]' : 'hey',authenticity_token : window._token}),
              dataType: "html",
              success: function(msg){
                 //ur msg;
              }});