<repo_name>JoshuaTPereira/rescue-mission<file_sep>/app/controllers/answers_controller.rb
class AnswersController < ApplicationController
  def create
    @answer = Answer.new(answer_params)
    @answer.write_attribute(:question_id, params[:question_id])

    if @answer.save
      redirect_to Question.find(params[:question_id])
    else
      flash.now[:errors] = @answer.errors.full_messages.join(', ⚠️').prepend('⚠️')
      @question = Question.find(params[:question_id])
      @answers = @question.answers
      render :'questions/show'
    end
  end

  def edit
    @answer = Answer.find(params[:id])
  end

  def update
    if params[:description]
      @answer = Answer.find(params[:id])
      @answer.description = answer_params[:description]
      @question = @answer.question

      if @answer.save
        flash[:notice] = "Answer was successfully updated"
        redirect_to @question
      else
        flash[:error] = @answer.errors.full_messages.join(', ')
        render :edit
      end
    else
      @answer = Answer.find(params[:id])
      @question = @answer.question
      @selected = Answer.where(question: @question).where(selected: true)
      @selected.each do |select|
        select.selected = false
        select.save
      end
      @answer.selected = true
      @answer.save
      redirect_to @question
    end
  end

  def destroy
    @answer = Answer.find(params[:id])
    @question = @answer.question
    @answer.destroy
    redirect_to @question
  end

  private

  def answer_params
    params.require(:answer).permit(:description)
  end
end
<file_sep>/app/controllers/questions_controller.rb
class QuestionsController < ApplicationController
  def index
    @questions = Question.all
  end

  def show
    @question = Question.find(params[:id])
    @answers = @question.answers
    selected = @answers.find_by(selected: true)
    @answers = @answers.select do |answer|
      answer.selected == false
    end
    # @answers.order(:created_at)
    @answers.unshift(selected)
    @answer = Answer.new
  end

  def new
    @question = Question.new
  end

  def create
    @question = Question.new(question_params)

    if @question.save
      redirect_to @question
    else
      flash.now[:errors] = @question.errors.full_messages.join(', ⚠️').prepend('⚠️')
      render :new
    end
  end

  def edit
    @question = Question.find(params[:id])
  end

  def update
    @question = Question.find(params[:id])
    @question.update_attributes(question_params)

    if @question.valid?
      flash[:notice] = "Question was successfully updated"
      redirect_to @question
    else
      flash[:error] = @question.errors.full_messages.join(', ')
      render :edit
    end
  end

  def destroy
    @question = Question.find(params[:id])
    @question.destroy
    redirect_to '/'
  end

  private

  def question_params
    params.require(:question).permit(:title, :description)
  end
end
