从控制台加入两个表
Join on two tables from the console
我有以下 tables...
class QuestionEvent < ActiveRecord::Base
...
belongs_to :recipient, :class_name => "User", :foreign_key => "recipient_id"
...这让我可以...
2.1.5 :001 > qe = QuestionEvent.find 475282
QuestionEvent Load (0.4ms) SELECT `question_events`.* FROM `question_events` WHERE `question_events`.`id` = 475282 LIMIT 1
=> #<QuestionEvent id: 475282, question_id: 112307, initiated_by_id: 17, recipient_id: 10696, "2013-03-13 13:08:14", updated_at: "2013-03-13 13:08:14", updated_question_values: nil, changed_tag: nil>
2.1.5 :002 > qe.recipient
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 10696 LIMIT 1
=> nil
我正在寻找的是一个查询,我可以从控制台 运行 向我显示 recipients
为零的所有 QuestionEvents。在上面的例子中,有一个 recipient_id,但是,那个 id 不在 User table.
我试过 QuestionEvent.includes(:recipient).where("recipient_id", nil)
但没有雪茄。
尝试:
QuestionEvent.where("question_events.recipient_id NOT IN (?)", User.pluck(:id))
我们可以使用 2 个查询
user_ids = User.pluck(:id)
QuestionEvent.where("recipient_id NOT IN (?)", user_ids)
我有以下 tables...
class QuestionEvent < ActiveRecord::Base
...
belongs_to :recipient, :class_name => "User", :foreign_key => "recipient_id"
...这让我可以...
2.1.5 :001 > qe = QuestionEvent.find 475282
QuestionEvent Load (0.4ms) SELECT `question_events`.* FROM `question_events` WHERE `question_events`.`id` = 475282 LIMIT 1
=> #<QuestionEvent id: 475282, question_id: 112307, initiated_by_id: 17, recipient_id: 10696, "2013-03-13 13:08:14", updated_at: "2013-03-13 13:08:14", updated_question_values: nil, changed_tag: nil>
2.1.5 :002 > qe.recipient
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 10696 LIMIT 1
=> nil
我正在寻找的是一个查询,我可以从控制台 运行 向我显示 recipients
为零的所有 QuestionEvents。在上面的例子中,有一个 recipient_id,但是,那个 id 不在 User table.
我试过 QuestionEvent.includes(:recipient).where("recipient_id", nil)
但没有雪茄。
尝试:
QuestionEvent.where("question_events.recipient_id NOT IN (?)", User.pluck(:id))
我们可以使用 2 个查询
user_ids = User.pluck(:id)
QuestionEvent.where("recipient_id NOT IN (?)", user_ids)