# frozen_string_literal: true module Admin class QuestionController < AdminController def index @questions = policy_scope Question.includes(:quiz).order("quizzes.name", { active: :desc }, :sort) end def new authorize Question @question = Question.new(active: true) @quizzes = policy_scope Quiz.all end def create authorize Quiz @quizzes = policy_scope Quiz.all @question = Question.create(process_question_params) if @question.persisted? redirect_to admin_questions_path, flash: { success: "Sucessfully created question" } else flash[:error] = "Failed to save question." render :new end end def view @question = Question.includes(:quiz).find(params[:question_id]) authorize @question end def edit @quizzes = policy_scope Quiz.all @question = Question.includes(:quiz).find(params[:question_id]) authorize @question end def update @quizzes = policy_scope Quiz.all @question = Question.find(params[:question_id]) authorize @question if @question.update_attributes(process_question_params) redirect_to admin_question_path(@question.to_i), flash: { success: "Sucessfully updated question" } else flash[:error] = "Failed to update question." render :edit end end def options @question = params[:question_id].present? ? Question.find(params[:question_id]) : Question.new authorize @question render layout: false end private def question_params params.require(:question).permit( :quiz_id, :question, :category, :attachment, :input_type, :sort, :active, :input_options, multi_choice: [], live_code: [:later, :html, :css, :js, :text] ) end def process_question_params question = question_params question[:input_options] = question_params[:multi_choice] unless question_params[:multi_choice].nil? question[:input_options] = question_params[:live_code] unless question_params[:live_code].nil? question.delete(:multi_choice) question.delete(:live_code) question end end end