I have two tables, “questions” and “test_questions”:
schema "questions" do has_one :test_question, TestQuestion field :question_type, :string, null: false field :body, :string, null: false end schema "test_questions" do belongs_to :test, Test belongs_to :question, Question field :position, :integer, null: false # question no. in the test end
Is there any efficient way to retrieve all questions that are not test questions? I tried something like the following, according to a StackOverflow answer (https://stackoverflow.com/a/19364694):
Repo.all(from q in Question, where: q.question_type == "long question" and not ^Repo.exists?(from tq in TestQuestion, where: tq.question_id == q.id), limit: 20 )
But I got the compilation error that q is an unbounded variable. I also tried to change q.id to ^q.id, but the compiler complained that q/0 is an undefined function.
Edit. It seems that the following query works:
Repo.all(from q in Question, left_join: tq in assoc(q, :test_question), where: q.question_type == "long" and is_nil(tq.id), limit: 20 )
but I’m not sure if this is really a correct or good way to solve the problem.