All threads / Scope has_many relationship

Ask A Question


You’re not receiving notifications from this thread.

Scope has_many relationship

Josh Goldman asked in Rails

I have four models

  1. Problem
  2. User
  3. Question
  4. Reply
class Problem < ApplicationRecord
  has_many :questions
class User < ApplicationRecord
  has_many :questions
  has_many :replies
class Question < ApplicationRecord
  belongs_to :problem
  belongs_to :user
  has_many :replies
class Reply < ApplicationRecord
  belongs_to :user
  belongs_to :question

The Reply model has an attribute answer:boolean, a question can have multiple replies and those replies can be marked as an answer to their associated question.

I am trying to create two scopes on the Question model one for answered questions and one for unanswered questions.

answered -> has at least one reply that was marked as an answer (boolean is true)
unanswered -> has no replies marked as an answer (boolean is true)

I would like to be able to use the scopes like this:


Also I will be displaying the user associated with the questions as well as the replies associated with the questions and the users associated with those replies, so think I need to use some type of "includes" statement so that I don't create N + 1 query.

I am stuck on how to achieve this?

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 39,609+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.