LoginSignup
2
1

More than 5 years have passed since last update.

Rails5 jQueryでsubmitした時の、InvalidAuthenticityTokenエラーを解消する

Last updated at Posted at 2019-01-04

発生した問題

jQuery を利用して、select ボックスを変更した際に、サブミットしたら ActionController::InvalidAuthenticityToken エラーが発生したのでその解決方法のメモ。

スクリーンショット 2019-01-04 17.50.07.png

環境

$ rails -v
Rails 5.2.2

$ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin18]
Gemfile.lock
jquery-rails (4.3.3)
  rails-dom-testing (>= 1, < 3)
  railties (>= 4.2.0)
  thor (>= 0.14, < 2.0)

bootstrap 4.2.1 を利用しています。

解決方法

<%= form_for @content, url: content_path(@content), html: {id: "edit_content_status"} do |form| %>
  <div class="form-group">
    <%= form.label :status %>
    <%= form.select :status, Content.status.keys, {}, :onchange => '$("#edit_content_status").submit();', class: "form-control" %>
  </div>
<% end %>

authenticity_token パラメータをPUT時に一緒に含めてあげればいいので、 form_for のオプションとして、 authenticity_token: true を設定してあげる。

<%= form_for @content, url: content_path(@content), html: {id: "edit_content_status"}, authenticity_token: true do |form| %>
  <div class="form-group">
    <%= form.label :status %>
    <%= form.select :status, Content.status.keys, {}, :onchange => '$("#edit_content_status").submit();', class: "form-control" %>
  </div>
<% end %>

すると、

Parameters: {"utf8"=>"✓", "authenticity_token"=>"L00Q20kOGwpkGAq6MI8DucZwtbCSsb4dkAz1ygZbOV+8ITLLaAoYSdi7w+khFr3TB04GaEPCSp0I9TLPrdbnWA==", "content"=>{"status"=>"published"}, "id"=>1}

といったように、 "authenticity_token" が iuput タグとして出力され、一緒に送信されるようになる。

補足情報

app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//

//= require jquery
//= require jquery.turbolinks
//= require turbolinks
//= require rails-ujs
//= require select2
//= require_tree .

Content モデルの情報

app/models/content.rb
# == Schema Information
#
# Table name: contents
#
#  id         :bigint(8)        not null, primary key
#  status     :boolean          default("draft"), not null
#

class Content < ApplicationRecord
  enum status: { draft: false, published: true }
...
end

rails-ujsとjquery-ujsは一緒に使うと、2回送信されたり、ブラウザの開発用コンソールに、アラートが表示されるので、jquery-ujsを使う方法は利用できませんでした。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1