Rails - 如何找到某个列值为nil的所有行,其中where()

时间:2014-06-23 08:55:56

标签: ruby ruby-on-rails-4

我想返回一个数组,其中包含名为bookings的表中的所有行,其中列returned_date为空。

到目前为止,我已经尝试了Booking.where("returned_date <> ''"),它选择了存在returned_date的所有记录,但我希望对此进行反向选择。

2 个答案:

答案 0 :(得分:6)

如果您想使用returned_datenull

Booking.where(returned_date: nil)

答案 1 :(得分:1)

您可以使用以下查询

Booking.where("returned_date IS NULL")

您可以在Booking模型中添加作为

的范围
Class Booking < ActiveRecord::Base

  scope :nil_returned_date, -> { where("returned_date IS NULL") }

end

然后将其称为Booking.nil_returned_date