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

时间:2016-10-11 10:32:29

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-3.1

我需要在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})

2 个答案:

答案 0 :(得分:2)

要在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])

答案 1 :(得分:0)

使用ActiveRecord chainingArray-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)