InvalidAuthenticityToken error with remote_form_for

Hi All -

I have a form_for that I’m trying to convert to remote_form_for, and I
keep get this error:

ActionController::InvalidAuthenticityToken
(ActionController::InvalidAuthenticityToken):
/usr/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/request_forgery_protection.rb:86:in
verify_authenticity_token' /usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:178:insend’
/usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:178:in
evaluate_method' /usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/callbacks.rb:166:incall’
/usr/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/filters.rb:225:in
`call’…

My form works fine without the ajax call:

<% form_for :vendor do |f| -%>

<%= f.text_field :name, :size => 15 %> <%= f.text_field :location, :size => 15 %> <%= f.submit 'save' %> <% end -%>

– partial :

<% @vendor = vendor %>

<%= vendor.name %> <%= vendor.location %>

– controller :

def create
@vendor = Vendor.new(params[:vendor])
if @vendor.save
respond_to do |format|
flash[:notice] = “New vendor #{@vendor.name} was saved!”
format.html { redirect_to vendors_path }
format.js
end
end
end

– rjs :

page.replace_html ‘flasher’, flash[:notice] unless flash[:notice].blank?
page.insert_html :after, ‘vendors_title’,
:partial => ‘vendor’,
:object => Vendor.find(:all, :order => ‘name’)

I tried adding sessions to my app with rake db:sessions:create and rake
db:migrate, and I also enabled the :secret in my application.rb…

Please help :slight_smile:

I tried using submit_to_remote (or link_to_remote) to submit the
form_for and it worked:

<% form_for :vendor do |f| -%>
<%= f.text_field :name, :size => 15 %>
<%= f.text_field :location, :size => 15 %>
<%# f.submit ‘save’ %>
<%= link_to_remote ‘save’,
:url => { :action => ‘create’, :id => @vendor } %>
<% end -%>

and in the controller:

def create
@vendor = Vendor.new(params[:vendor])
if @vendor.save
respond_to do |format|
format.html { redirect_to vendors_path }
format.js
end
end
end

Of course, I have a create.js.rjs template to handle the ajax events on
the page.

If nobody answered this yet, the reason it’s not working is that your
link doesn’t serialize the authenticity_token field. Just put:

<%= link_to_remote ‘save’,
:url => { :action => ‘create’, :id => @vendor }, :with =>
‘authenticity_token’ %>

and that should get you on the right path.

HTH