我有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
答案 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
。使用迁移将其删除。
为什么需要进行上述更改?
嵌套关系中外键user_id
的不必要的存储过程。
如果我们的答案包含问题和用户,而该问题不属于相应用户,该怎么办?在关联从属表时,请遵循 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 } )