Good day. It is impossible to implement the following script using devise: User logs in. User opens a form to create an object. User logs out. User tries to create an object through the User form on a login page with notification.

The problem is that when I try to send a request from the browser, the application crashes, on error:

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): 

routes.rb

 Rails.application.routes.draw do devise_for :users, path: '/', path_names: { sign_in: 'login' } resources :questions, only: [:index, :new, :show, :create, :destroy] do resources :answers, only: [:create, :destroy], shallow: true end root 'questions#index' end 

controller

  class AnswersController < ApplicationController before_action :authenticate_user!, only: [:create, :destroy] def create @question = Question.find(params[:question_id]) @answer = @question.answers.new(answer_params) @answer.user = current_user @answer.save redirect_to @question end 

The form

 - if user_signed_in? = form_for [@question, @answer] do |f| .errors .form-group = f.label :body, t('.you_answer') = f.text_area :body, class: 'form-control' .form-group = f.submit t('.asked'), class: 'btn btn-primary' 

layout

 !!! %html %head %title ProSampleApp = csrf_meta_tags = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' = javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %body = render 'layouts/header' .container-fluid #main.col-md-10 - flash.each do |message_type, message| %div{'class' => "alert alert-#{message_type}"} - Array(message).each do |msg| %li= msg = yield 

app controller

 class ApplicationController < ActionController::Base protect_from_forgery with: :exception rescue_from ActiveRecord::RecordNotFound, with: :show404 protected def show404 render file: 'public/404.html', status: :not_found, layout: false end end 
  • Show your layout, does the csrf_meta_tags call in it? - cheops
  • Devise has nothing to do with it, it seems. There is no CSRF token in the request. Show how the query looks in the logs. In particular, params . - D-side
  • if you call authenticate_user! not through before_action , but through prepend_before_action , it works. - Alexander Shvaykin
  • ... haa, it looks like I'm wrong. And the explanation is in readme Devise . Maybe. Or again I am mistaken. It is necessary to understand in what order these before_action 's are called. And it doesn't hurt to know the version of Rails. - D-side

0