I have two forms with option remote: true
; one sends an Ajax request to create
action and the other one sends an Ajax request to destroy
action.
All work fines when JavaScript is enabled, but if I disable JavaScript, then I click, I get this error:
ActionController::InvalidAuthenticityToken PersonsController#create
Why this error is shown, and how can I fix it ?
note: I'm using Rails 4
When I use a normal form without option remote: true
, rails automatically inserts a hidden field for an authentication token, but when I use remote: true
in my form there is no such field in the HTML code. It seems like when there is remote
option, then Rails handles the authentication token differently, so how I can get this to work in both cases?
Bizarrely, this behaviour was changed in rails 4. http://www.alfajango.com/blog/rails-4-whats-new/
Rails forms now will not render the CSRF field in the form unless you explicitly define it as an option to your form:
<%= form_for @some_model, :remote => true, :authenticity_token => true do |f| %> <% end %>
Adding this option allows you to gracefully degrade to a HTML fallback if Javascript is switched off.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With