Ask A Question

Notifications

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
end
class User < ApplicationRecord
  has_many :questions
  has_many :replies
end
class Question < ApplicationRecord
  belongs_to :problem
  belongs_to :user
  has_many :replies
end
class Reply < ApplicationRecord
  belongs_to :user
  belongs_to :question
end

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:

problem.questions.answered
problem.questions.unanswered

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?

Reply
Join the discussion
Create an account Log in

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

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

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