Rails 4 - 如果在另一个 table 中不是特定记录,如何从 table 中 select 数据?

Rails 4 - How to select data from a table if in another table is not a specific record?

我有这个模型时间表:

class Question < ActiveRecord::Base
  has_many :closed_questions
end
class ClosedQuestion < ActiveRecord::Base
  belongs_to :question
  belongs_to :user
end

并且我正在尝试获取该用户未检查为已关闭的所有问题。

示例:

ID | Question
1  | Question A
2  | Question B
3  | Question C
4  | Question D

User 1 已检查 ID 为 3 的问题已关闭。如何获取问题ID的输出1, 2, 4?

提前致谢。

您可能想尝试这样的事情:

user = User.find(1)
Question.where.not(id: user.closed_questions.pluck(:question_id))

请注意,在 Rails 4 之前,您可能会看到它写成:

user = User.find(1)
Question.where("id NOT IN (?)", user.closed_questions.pluck(:question_id))