Rails - how to find all rows where a certain colum

2020-07-23 08:36发布

问题:

I want to return an array with all rows in a table called bookings where the column returned_date is empty.

So far I've tried Booking.where("returned_date <> ''"), which chose all the records where returned_date is present, but I want an inverse selection of this.

回答1:

If you mean to get with returned_date column be null:

Booking.where(returned_date: nil)


回答2:

You could do with the below query

Booking.where("returned_date IS NULL")

OR

You can add a scope in your Booking model as

Class Booking < ActiveRecord::Base

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

end

Then call it as Booking.nil_returned_date