markstewie
markstewie

Reputation: 9587

Rails 3 ActiveRecord nested associations select query

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.

Upvotes: 1

Views: 1584

Answers (1)

stfcodes
stfcodes

Reputation: 1380

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>)

Upvotes: 2

Related Questions