category.rbRAILS:リレーションズ(すべてのトピックからすべての答えを選択)
has_many :topics
topic.rb
belongs_to :category
has_many :answers
answer.rb
belongs_to :topic
質問:
どのように私はCategory.first.topics.answers.count
category.rbRAILS:リレーションズ(すべてのトピックからすべての答えを選択)
has_many :topics
topic.rb
belongs_to :category
has_many :answers
answer.rb
belongs_to :topic
質問:
どのように私はCategory.first.topics.answers.count
のようなクエリがhas_many :through
関係を使用して、プリフォームすることができます
# Category.rb
has_many :topics
has_many :answers, through: :topics
今、あなたはそうのようなすべてのトピックからすべての答えにアクセスすることができます。
Category.first.answers.count
スキーマ設定で設定されている場合(つまり、 )has_many :through
を使用していない、あなたはここで私たちは、ネストされた団体に参加した後、フィルターにwhere句を使用しているAnswers
で始まり、Category
Answers.joins(topic: :category).where(categories: { id: category_id })
に到達するためにjoin
秒のカップルを利用したいと思いますアウトcategory_id
ノートで:私は、これは正しい構文であると思うが、私は本当にhas_manyのを忘れtopic
が複数、そこcategory
と周りいじる必要があるかもしれません:通じ、それは常に素晴らしいです1の多くの解を持つ問題。ありがとうございました! – Src