首页 > 解决方案 > ActionController::UnknownFormat 在 AnswerController#results

问题描述

这是我得到的错误

AnswerController#results 缺少此请求格式和变体的模板。request.formats: ["text/html"] request.variant: [] 注意!对于 XHR/Ajax 或 API 请求,此操作通常会响应 204 No Content:空白屏幕。由于您是在 Web 浏览器中加载它,我们假设您希望实际呈现一个模板,而不是什么都没有,所以我们显示一个错误是非常清楚的。如果您期望 204 No Content,请继续。这就是您将从 XHR 或 API 请求中获得的信息。试一试。

我不确定“缺少模板”是什么意思。我也不确定为什么会收到此错误。我将提供我认为可能与此问题相关的所有代码。

answer_controller.rb

class AnswerController < ApplicationController
  def create
    @answer = current_quiz.answers.create(question_id: question, choice_id: choice)
    redirect_to question_quiz_path(current_quiz)
  end

  def results
    @choices = choices_hash
    @results = questions.map do |question|
      {
        question.question => CountChoicesService.call(question.id)
      }
    end
  end

  private

  def question
    @question ||= params[:question]
  end

  def choice
    @choice ||= params[:choice]
  end

  def choices
    @choices ||= Array.wrap(Choice.all)
  end

  def choices_hash
    choices_hash = {}
    choices.each { |choice| choices_hash[choice.id] = choice.choice }
    choices_hash
  end

  def questions
    @questions ||= Array.wrap(Question.all)
  end
end

count_choices_service.rb

class CountChoicesService
  def self.call(question_id)
    new(question_id).call
  end

  def call
    only_finished.to_a
  end

  private

  attr_reader :question_id

  def initialize(question_id)
    @question_id = question_id
  end

  def count_choices_by_question
    Answer
      .select("COUNT(choice_id), choice_id")
      .where(question_id: question_id)
      .group(:choice_id)
      .order(:choice_id)
  end

  def only_finished
    count_choices_by_question.where(answers: { quiz_id: quiz_ids })
  end

  def finished_quizzes
    Quiz.finished
  end

  def quiz_ids
    @quiz_ids = finished_quizzes.map(&:id)
  end
end

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  protected

  def check_existing_quiz!
    redirect_to question_quiz_path(current_quiz) if current_quiz.present?
  end

  def check_finished_quiz!
    redirect_to results_answer_index_path if quiz_finished?
    redirect_to new_quiz_path unless current_quiz.present?
  end

  private

  def current_quiz
    @current_quiz ||= session[:current_quiz] && Quiz.find_by(id: session[:current_quiz])
  end

  def quiz_finished?
    current_quiz.present? && !current_quiz.is_active
  end
end

quiz_controller.rb

class QuizController < ApplicationController
  before_action :check_existing_quiz!, only: [:new, :create]
  before_action :check_finished_quiz!, only: [:question]

  def new
    @quiz = Quiz.new
  end

  def create
    @quiz = Quiz.create(is_active: true)
    session[:current_quiz] = @quiz.id
    redirect_to question_quiz_path(@quiz)
  end

  def question
    @question = NextQuestionService.next(current_quiz)
    if @question
      @answer = Answer.new
    else
      current_quiz.update_attribute(:is_active, false)
      redirect_to results_answer_index_path
    end
  end
end

种子.rb

Question.destroy_all
Choice.destroy_all

data_file = Rails.root.join('db', 'data.json')
collection = JSON.parse(File.read(data_file))['questions']

collection.each do |item|
  question = Question.create!(question: item['question'])
  item['choices'].each do |choice|
    question.choices.create!(choice: choice)
  end
end

p "Created #{Question.count} questions"
p "Created #{Choice.count} choices"

数据.json

{
  "questions": [
    {
      "question": "Who is Luke Skywalker’s dad?",
      "choices": ["French Montana", "Anakin Skywalker", "The Dude"]
    },
    {
      "question": "Which is the only film of the original six in which desert planet Tatooine doesn’t appear?",
      "choices": ["The Last Jedi", "Revenge of the Sith", "The Empire Strikes Back"]
    },
    {
      "question": "Who kills Jabba The Hutt?",
      "choices": ["Princess Leia", "Frodo", "Han Solo"]
    },
    {
      "question": "What was Luke Skywalker’s original surname?",
      "choices": ["Starkiller", "The Phantom", "Arnold Schwarzenegger"]
    },
    {
      "question": "What planet do Wookiees come from?",
      "choices": ["Venus", "Jupiter", "Kashyyk"]
    }
  ]
}

架构.rb

ActiveRecord::Schema.define(version: 2018_09_05_120106) do

  create_table "answers", force: :cascade do |t|
    t.integer "quiz_id"
    t.integer "question_id"
    t.integer "choice_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["choice_id"], name: "index_answers_on_choice_id"
    t.index ["question_id"], name: "index_answers_on_question_id"
    t.index ["quiz_id"], name: "index_answers_on_quiz_id"
  end

  create_table "choices", force: :cascade do |t|
    t.text "choice"
    t.integer "question_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["question_id"], name: "index_choices_on_question_id"
  end

  create_table "questions", force: :cascade do |t|
    t.text "question"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "quizzes", force: :cascade do |t|
    t.boolean "is_active"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

路线.rb

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :quiz, only: [:new, :create] do
    member do
      get 'question'
    end
  end

  resources :answer, only: [:create] do
    collection do
      get 'results'
    end
  end

根到:'测验#问题'

得到 '*path' => 重定向('/') 结束

服务器日志

ActionController::UnknownFormat (AnswerController#results is missing a template for this request format and variant.

request.formats: ["text/html"] request.variant: []

NOTE! For XHR/Ajax or API requests, this action would normally respond with 204 No Content: an empty white screen. Since you're loading it in a web browser, we assume that you expected to actually render a template, not nothing, so we're showing an error to be extra-clear. If you expect 204 No Content, carry on. That's what you'll get from an XHR or API request. Give it a shot.

actionpack (5.2.1) lib/action_controller/metal/implicit_render.rb:55:in `default_render'
actionpack (5.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `block in send_action'
actionpack (5.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `tap'
actionpack (5.2.1) lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action'
actionpack (5.2.1) lib/abstract_controller/base.rb:194:in `process_action'
actionpack (5.2.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (5.2.1) lib/abstract_controller/callbacks.rb:42:in `block in process_action'
activesupport (5.2.1) lib/active_support/callbacks.rb:132:in `run_callbacks'
actionpack (5.2.1) lib/abstract_controller/callbacks.rb:41:in `process_action'
actionpack (5.2.1) lib/action_controller/metal/rescue.rb:22:in `process_action'
actionpack (5.2.1) lib/action_controller/metal/instrumentation.rb:34:in `block in process_action'
activesupport (5.2.1) lib/active_support/notifications.rb:168:in `block in instrument'
activesupport (5.2.1) lib/active_support/notifications/instrumenter.rb:23:in `instrument'
activesupport (5.2.1) lib/active_support/notifications.rb:168:in `instrument'
actionpack (5.2.1) lib/action_controller/metal/instrumentation.rb:32:in `process_action'
actionpack (5.2.1) lib/action_controller/metal/params_wrapper.rb:256:in `process_action'
activerecord (5.2.1) lib/active_record/railties/controller_runtime.rb:24:in `process_action'
actionpack (5.2.1) lib/abstract_controller/base.rb:134:in `process'
actionview (5.2.1) lib/action_view/rendering.rb:32:in `process'
actionpack (5.2.1) lib/action_controller/metal.rb:191:in `dispatch'
actionpack (5.2.1) lib/action_controller/metal.rb:252:in `dispatch'
actionpack (5.2.1) lib/action_dispatch/routing/route_set.rb:52:in `dispatch'
actionpack (5.2.1) lib/action_dispatch/routing/route_set.rb:34:in `serve'
actionpack (5.2.1) lib/action_dispatch/journey/router.rb:52:in `block in serve'
actionpack (5.2.1) lib/action_dispatch/journey/router.rb:35:in `each'
actionpack (5.2.1) lib/action_dispatch/journey/router.rb:35:in `serve'
actionpack (5.2.1) lib/action_dispatch/routing/route_set.rb:840:in `call'
rack (2.0.5) lib/rack/tempfile_reaper.rb:15:in `call'
rack (2.0.5) lib/rack/etag.rb:25:in `call'
rack (2.0.5) lib/rack/conditional_get.rb:25:in `call'
rack (2.0.5) lib/rack/head.rb:12:in `call'
actionpack (5.2.1) lib/action_dispatch/http/content_security_policy.rb:18:in `call'
rack (2.0.5) lib/rack/session/abstract/id.rb:232:in `context'
rack (2.0.5) lib/rack/session/abstract/id.rb:226:in `call'
actionpack (5.2.1) lib/action_dispatch/middleware/cookies.rb:670:in `call'
activerecord (5.2.1) lib/active_record/migration.rb:559:in `call'
actionpack (5.2.1) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (5.2.1) lib/active_support/callbacks.rb:98:in `run_callbacks'
actionpack (5.2.1) lib/action_dispatch/middleware/callbacks.rb:26:in `call'
actionpack (5.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:61:in `call'
web-console (3.6.2) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.6.2) lib/web_console/middleware.rb:30:in `block in call'
web-console (3.6.2) lib/web_console/middleware.rb:20:in `catch'
web-console (3.6.2) lib/web_console/middleware.rb:20:in `call'
actionpack (5.2.1) lib/action_dispatch/middleware/show_exceptions.rb:33:in `call'
railties (5.2.1) lib/rails/rack/logger.rb:38:in `call_app'
railties (5.2.1) lib/rails/rack/logger.rb:26:in `block in call'
activesupport (5.2.1) lib/active_support/tagged_logging.rb:71:in `block in tagged'
activesupport (5.2.1) lib/active_support/tagged_logging.rb:28:in `tagged'
activesupport (5.2.1) lib/active_support/tagged_logging.rb:71:in `tagged'
railties (5.2.1) lib/rails/rack/logger.rb:26:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.2.1) lib/action_dispatch/middleware/remote_ip.rb:81:in `call'
actionpack (5.2.1) lib/action_dispatch/middleware/request_id.rb:27:in `call'
rack (2.0.5) lib/rack/method_override.rb:22:in `call'
rack (2.0.5) lib/rack/runtime.rb:22:in `call'
activesupport (5.2.1) lib/active_support/cache/strategy/local_cache_middleware.rb:29:in `call'
actionpack (5.2.1) lib/action_dispatch/middleware/executor.rb:14:in `call'
actionpack (5.2.1) lib/action_dispatch/middleware/static.rb:127:in `call'
rack (2.0.5) lib/rack/sendfile.rb:111:in `call'
railties (5.2.1) lib/rails/engine.rb:524:in `call'
puma (3.12.0) lib/puma/configuration.rb:225:in `call'
puma (3.12.0) lib/puma/server.rb:658:in `handle_request'
puma (3.12.0) lib/puma/server.rb:472:in `process_client'
puma (3.12.0) lib/puma/server.rb:332:in `block in run'
puma (3.12.0) lib/puma/thread_pool.rb:133:in `block in spawn_thread'

我已经被困了很长时间了,我找不到任何与我的问题相关的答案。

标签: ruby-on-railsruby

解决方案


推荐阅读