So, I have a Model House
, and a house can have_many
Room
s.
I would like to delete all records of House
that have no Room
s.
I've tried
House.includes(:room).having('room.id IS NULL')
which errors, as does
House.all().where(:room.count == 0)
and many other things that I've tried along the same lines.
I'm probably missing something really straightforward, anyone have any ideas?
The association should be plural
House.includes(:rooms).where(rooms: { id: nil }).count
And you should be able to delete them using
ids = House.includes(:rooms).where(rooms: { id: nil }).pluck(:id)
House.where(id: ids).delete_all
# Note: I'm leaving this as reference. It seems to raise an error.
# House.includes(:rooms).where(rooms: { id: nil }).delete_all
Otherwise you can work with a little bit of pure SQL and perform a DELETE
statement directly using a join
.
House.includes(:rooms).where('rooms.id IS NULL')
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.