25

Using rails 4, and trying to add a file field to an existing form, using simple_form and paperclip.

Here's the critical part of the form:

<%= simple_form_for(@employee, html: { class: 'form-horizontal requires', multipart: true}, remote: true) do |f| %>

    <%= f.input :avatar %>

<% end %>

Everything works ok, unless I actually submit the form with an uploaded file. Then, I get this:

ActionController::InvalidAuthenticityToken in EmployeesController#update

What am I doing wrong here?

croceldon
  • 4,511
  • 11
  • 57
  • 92
  • 2
    I believe your answer is [here][1] Looks like new with rails 4. [1]: http://stackoverflow.com/questions/16258911/rails-4-authenticity-token – Arthur Frankel Sep 03 '13 at 15:59
  • The problem is combining multipart with remote: true. This will force the form submission as HTML rather than JS. Removing the multipart will force it as JS, but then you cannot upload a file. Obviously, this is a bug, and the remotipart gem apparently is a fix. – Daniel Viglione Jun 15 '18 at 21:41

2 Answers2

21

The simplest solution would just be to add authenticity_token: true to your form. Like this:

<%= form_for @employee, html: { class: 'form-horizontal requires'}, multipart: true, remote: true, authenticity_token: true  do |f| %>
  <%= f.input :avatar %>
<% end %>
Hunter
  • 1,667
  • 17
  • 24
  • 2
    adding `authenticity_token: true` worked like a charm :-) – Avishai Jun 16 '16 at 16:50
  • 2
    be warned that `remote: true` option will be ignored and the form is submitted as `html`. If you want to submit the form as `js` look at [William](http://stackoverflow.com/a/21029501/1079609) answer. – golfadas May 11 '17 at 19:43
20

I was with the same problem. <%= token_tag form_authenticity_token %> didn't work for me.

Install gem remotipart solved my problem. remotipart

Ricardo Binns
  • 3,228
  • 6
  • 44
  • 71
William Weckl
  • 2,435
  • 4
  • 26
  • 43
  • 5
    This is the actual answer if you are trying to submit a file using remote: true and wanting to respond using a js.erb file. Install the remotipart gem (very quick and easy) and it works like a charm. – David Routen Dec 18 '14 at 22:55