How to catch ids getting created and compare their attributes in rails active record

user3576036 Source

I have a Question model and a PossibleAnswer model the tables are as follows.

possible_answers

create_table "possible_answers", force: :cascade do |t|
    t.integer  "question_id"
    t.string   "title"
end

questions

create_table "questions", force: :cascade do |t|
    t.string   "title"
    t.string   "right_answer"
end

The association is (you could have guessed already but anyway)

Question.rb

class Question < ActiveRecord::Base
  has_many :possible_answers
end 

PossibleAnswer.rb

class PossibleAnswer < ActiveRecord::Base
   belongs_to :question
end

Now I have a form where all the questions are posted with their respective choices. I have a controller to submit the answers by selecting the choices.

class RepliesController < ApplicationController
   def create
    @quiz = Quiz.find(params[:quiz_id])
    @reply = @quiz.replies.build reply_params
    if @reply.save
      redirect_to @quiz, notice: "Thank you for taking the quiz"
    end
  end
  def reply_params
    params.require(:reply).permit({ answers_attributes: [ :value, :question_id, :possible_answer_id ] })
  end
end

Now this create method is working fine. Once the user submits the quiz, the following data is created.

{"answers_attributes"=>{"0"=>{"possible_answer_id"=>"10", "question_id"=>"6"}}, "commit"=>"Finish quiz", "quiz_id"=>"1"}

Here the possible_answer_id is the option which user selected and the possible answer belongs to the question_id.

My question is, how can I compare the title from this possible_answer_id to the right_answer of the question_id.

I tried using find params and passing the id but didnt work. Can anybody please help me here. I have a come a long way building this app and stuck here now.

ruby-on-rails

Answers

answered 3 months ago David Sigley #1

Have you thought about adding a :correct, :boolean, default: :false to your possible_answers table. That way when the user selects the answer you're able to find it and see if it's correct.

Having the answer string in both question and possible_answers isn't the most efficient solution.

Alternatively (If you want to keep the answer in the questions table) you could change right_answer to possible_answer_id and have a has_one :possible_answer, as: :right_answer. So you can do:

question.possible_answers   # returns list
question.right_answer       # returns just the single record of the correct answer

comments powered by Disqus