【问题标题】:Rails 4 - How to select data from a table if in another table is not a specific record?Rails 4 - 如果另一个表中不是特定记录,如何从表中选择数据?
【发布时间】:2023-04-10 02:12:02
【问题描述】:

我有这个模型时间表:

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 的问题已关闭。如何获取问题ID1, 2, 4的输出?

提前谢谢你。

【问题讨论】:

    标签: mysql ruby-on-rails ruby activerecord model


    【解决方案1】:

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

    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))
    

    【讨论】:

    • 只是为了改进你可以使用Question.where.not(id: user.closed_questions.pluck(:question_id) 实现相同的代码
    • 谢谢。更新了您的建议。
    猜你喜欢
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2022-01-21
    • 2020-10-08
    • 1970-01-01
    • 2012-01-23
    • 2021-08-05
    • 2021-12-14
    相关资源
    最近更新 更多