ActionController::InvalidAuthenticityToken when di

2020-02-20 05:54发布

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

Update

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?

4条回答
相关推荐>>
2楼-- · 2020-02-20 06:25

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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-20 06:42

If there is no csrf field(a hidden field) inside the form, the submission can't be authenticated by Rails server.

If you make the form by form_tag, this situation will happen. The better approach is to use form_for for a resource(new object or an existing object in db) and csrf field will be built by Rails automatically.

查看更多
贼婆χ
4楼-- · 2020-02-20 06:47

In my case i just had to add this line in my page:

 <%= csrf_meta_tags %>
查看更多
smile是对你的礼貌
5楼-- · 2020-02-20 06:48

Me too faced the same problem. I have used form_tag to create custom remote form, but i got the the following error,

 ActionController::InvalidAuthenticityToken

I found that this is because in rail 4 wont add authenticity toke by default, so i added the following line in application.rb file,

 config.action_view.embed_authenticity_token_in_remote_forms = true

which automatically verify the toke when submitting the remote forms. This solves the problem for me. Hope this will help some one.

查看更多
登录 后发表回答