実現したいこと
Railsでアンケート機能を作っているのですが、下記の想定しているレスポンスデータに整形できません。
親(questionnaire)に子(choice)のデータをぶらさげて、choiceのデータ内に孫(answer)のカウント数も格納させたいです。
わかる方がいらっしゃいましたら、アドバイスを頂けますと幸いです。
想定しているレスポンス
[ { id: 1, text: "朝ごはんは何派派?", choices: [ { id: 1, choice: "パン", asnwer_counts: 4 }, { id: 2, choice: "和食", asnwer_counts: 1 }, { id: 3, choice: "グラノーラ", asnwer_counts: 2 }, ] }, { id: 2, text: "好きなスポーツは?", choices: [ { id: 4, choice: "テニス", asnwer_counts: 2 }, { id: 5, choice: "水泳", asnwer_counts: 2 }, { id: 6, choice: "バドミントン", asnwer_counts: 3 }, ] }, ]
テーブル構成
親:Questionnaireテーブル
| id | text |
|---|---|
| 1 | 朝ごはんは何派? |
| 2 | 好きなスポーツは? |
子:Choiceテーブル
| id | choice | questionnaire_id |
|---|---|---|
| 1 | パン | 1 |
| 2 | 和食 | 1 |
| 3 | グラノーラ | 1 |
| 4 | テニス | 2 |
| 5 | 水泳 | 2 |
| 6 | バドミントン | 2 |
孫:Answerテーブル(user_idは誰が投票したか)
| id | user_id | choice_id | questionnaire_id |
|---|---|---|---|
| 1 | 2 | 3 | 1 |
| 2 | 3 | 1 | 1 |
| 3 | 4 | 1 | 1 |
| 4 | 5 | 2 | 1 |
| 5 | 6 | 3 | 1 |
| 6 | 7 | 1 | 1 |
| 7 | 8 | 1 | 1 |
| 8 | 2 | 6 | 2 |
| 9 | 3 | 5 | 2 |
| 10 | 4 | 6 | 2 |
| 11 | 5 | 4 | 2 |
| 12 | 6 | 4 | 2 |
| 13 | 7 | 6 | 2 |
| 14 | 8 | 5 | 2 |
アソシエーション
親:Questionnaireテーブル
class Questionnaire < ApplicationRecord belongs_to :user has_many :choices has_many :answers, through: :choices end
子:Choiceテーブル
class Choice < ApplicationRecord belongs_to :questionnaire has_many :answers end
孫:Answerテーブル
class Answer < ApplicationRecord belongs_to :user belongs_to :choice belongs_to :questionnaire end
試したこと
①
Ruby
1@questionnaires = Questionnaire.joins(:choices, :answers).select("questionnaires.*, choices.*, count(*) as answers").group("choices.id")
・joinしているのでquestionnaireテーブルのデータがたくさんできてしまう
・answerのカウント数ではなく、配列で取得されてしまう
②
@questionnaires = Questionnaire.includes(:choices, :answers).joins(:choices, :answers).select("choices.*, answers.*")
・1つのquestionnaireデータにつき、1つのchoiceのデータがしか所得されない
・そもそもanswerデータが取得できない
回答1件
あなたの回答
tips
プレビュー