简体   繁体   中英

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

I have this model schedule:

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

And I am trying to fetch all questions for a user that this user didn't check as closed.

Example:

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

User 1 checked question with ID 3 as closed. How to get the output of question IDs 1, 2, 4 ?

Thank you in advance.

You may want to try something like this:

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

Note that prior to Rails 4 you might see this written as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM