rails 如何在 rails 中获取以下查询

rails how to get the following query in rails

我需要在 rails 中获得以下输出,我该怎么做?

SELECT "booking_rooms".* FROM "booking_rooms" INNER JOIN "bookings" ON "bookings"."id" = "booking_rooms"."booking_id" WHERE "booking_rooms"."room_id" IN (22, 27, 21) AND ("bookings"."start_date" <= '2016-10-16' AND "bookings"."end_date" > '2016-10-12')

我试过了:

BookingRoom.joins(:booking).where(room_id: self.booking_rooms.map(&:room_id), bookings: { start_date:self.end_date,end_date:self.start_date})

使用 ActiveRecord chaining and Array-Conditions 你可以做类似的事情:

BookingRoom.joins(:booking).
     where(room_id: self.booking_rooms.map(&:room_id)).
     where(bookings: { "start_date <= ? AND end_date > ?" }, self.start_date, self.end_date)

要在 where 语句中使用条件,请参阅“Conditions”文档。

试试这个:

BookingRoom.joins(:booking)
        .where(room_id:self.booking_rooms.map(&:room_id)
        .where(bookings: { "start_date <= :start_date AND end_date > :end_date" },start_date: params[:start_date], end_date: params[:end_date])