1

I'm trying to make an API for a quiz admin I have made.

I have a Quiz model which has_many Questions and has_many Results The Question model also has_many Answers

I want the url /data/quiz/7 to return all the Questions+Answers and Results to the Quiz with id=7

Here is the method for this I have at the moment.

def quiz
    @quiz = Quiz.find(params[:id])

    @questions = @quiz.questions.select('id, content') # returns only selected fields
    @results = @quiz.results.select('id, content, points_limit') # returns only selected fields

    @questions.each do |question|
        question['answers'] = question.answers.select('id, content, points') #returns whole object
    end

    @return = Hash.new
    @return['questions'] = @questions
    @return['results'] = @results

    respond_to do |format|
        format.json { render json: @return }
        format.xml { render xml: @return }
    end
end

Everything works EXCEPT the answers are returning the FULL answer object including created-at, id, updated-at etc etc and all I want are the fields selected in the query like I have.

Why is the .select working for @questions and @results but not the associated @answers?

No matter what I try it seems to ignore the select statement for the answers loop and always return the full object.

--

In console... I know doing the same thing

question.answers.select('id, content, points')

returns exactly what I'm after. So it's something to do with the way I'm putting it into the Array/Hash I'm guessing but still can't work it out.

1 Answer 1

2

I think if you try something like this it will work:

@answers = Answer.select([:id, :content, :points])
                 .where(question_id: @questions.pluck(:id))

This is the same as:

SELECT id, content, points
FROM answers
WHERE question_id in (<question_ids array>)
Sign up to request clarification or add additional context in comments.

1 Comment

That works but not the way I really want it to unfortunately. This dumps all the answers out together where as I want each set of answers nested with the appropriate question. Thanks for your answer though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.