Reputation: 69
I have a Class named Question and a related Class named Answers. I want to return the Question in JSON format, together with the grouped count of the Answers. As an example:
["question":"What's 3 x 4?", ["12":15, "10":2]]
So 15 respondents have said it's 12 and 2 have said it's 10.
Now, I can return the array from the Answers, using the following code:
@answers = Answer.where(:question_id => params[:id]).count(:group => 'answer')
I can also add the Answers for each user, using the following code:
format.json { render json: @question , :include => :answers, :conditions => {:answers => { :user_id => user_id}}}
But I am unable to return both the Question, together with the counted, grouped by array of results...
Please advice?
Upvotes: 0
Views: 221
Reputation: 1764
You could use the jbuilder gem for building your own json-templates.
# /app/views/question.show.json.jbuilder
if question
json.id question.id
json.answers do |answer|
json.answer_text answer.text
json.answer_count answer.count
end
else
nil
end
Upvotes: 1