查询所有不包含特定关联的记录

时间:2019-02-25 12:11:38

标签: ruby-on-rails ruby-on-rails-4

我有3种型号:

Questions
-- belongs_to :user
-- has_many :answers
Answers
-- belongs_to :user
-- belongs_to :question
Users
-- has_many :questions
-- has_many :answers

如何查询用户未回答的所有问题?

我尝试了类似的方法,但是它没有返回任何问题:

Question.includes(:answers).where.not( :answers => { :user_id => current_user.id } )

更新

最终做了这样的事情:

class User < ActiveRecord::Base
    has_many :answers
    has_many :questions, through: :answers
end

class Answer < ActiveRecord::Base
    belongs_to :user
    belongs_to :question
end

class Question < ActiveRecord::Base
  has_many :answers
  has_many :users, through: :answers
end

然后,我可以使用以下方法获得未解答的问题:

@answered = current_user.questions
@unanswered = Question.all - @answered_questions

2 个答案:

答案 0 :(得分:1)

您的关联必须像,

Users
-- has_many :questions
-- has_many :answers, through: :questions
Questions
-- belongs_to :user
-- has_many :answers
Answers
-- belongs_to :question
-- delegate :user, to: :question

user_id表中不需要外键answers。使用迁移将其删除。

为什么需要进行上述更改?

  1. 嵌套关系中外键user_id的不必要的存储过程。

  2. 如果我们的答案包含问题和用户,而该问题不属于相应用户,该怎么办?在关联从属表时,请遵循 OOAD 。阅读Rails ActiveRecord Association

答案 1 :(得分:0)

左加入拯救世界!

Question.includes('left join answers on answers.question_id = questions.id').
includes('left join users on users.id = answers.user_id').
where( users: { id: nil } )