On this feature I'm adding to my school's app, an User has a new Checkup (a short English test) being presented by the system for them to do every 4 weeks. I want to build a query that always retrieves from the database a Checkup that hasn't been previously answered by the student. Since the models are associated, I believe this is simple, but I do not know how to code the query using Rails (have done research and wasn't able to find an answer). There are three models to be considered here: User, Answer and Checkup. I have a separate Answer model for the answers the students give, because they have to be processed separately due to other features of the app. This is the User model:
class User < ApplicationRecord
has_many :answers
end
This is the Answer model:
class Answer < ApplicationRecord
belongs_to :user
belongs_to :checkup
end
And this is the Checkup model
class Checkup < ApplicationRecord
has_many :answers
end
In the controller of the page where the Checkup is shown, I wish to have a variable in the page's action that holds the retrieved Checkup:
def exams
@next_checkup = #the ActiveRecord query goes here
end
The query needs to retrieve a Checkup that doesn't have in its related answers an answer given by the current user (the user of an answer can be retrieved by the attribute "user_id"). How should I code the query? Thanks!
CodePudding user response:
I would try:
@next_checkup = Checkup.where.not(id: current_user.answers.pluck(:checkup_id)).first