For a reservation form, I'm trying to get all the unavailable rooms for the selected dates. I'm performing this action in the hotels_controller.
Issue
I cannot seem to join the rooms with the reservation properly, as I get the error:
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column rooms.hotel does not exist
LINE 1: ...."room_id" = "rooms"."id" WHERE "accommoda...
^
: SELECT DISTINCT "rooms".* FROM "rooms" INNER JOIN "reservations" ON "reservations"."room_id" = "rooms"."id" WHERE "rooms"."hotel" = $1 AND (reservations.arrival <= '2019-11-22' AND '2019-11-23' < reservations.departure) LIMIT $2):
Code
hotels_controller
@unavailable_rooms = Room.joins(:reservations).where(hotel: hotel).where("reservations.arrival <= ? AND ? < reservations.departure", arrival, departure).distinct
models
class Reservation < ApplicationRecord
belongs_to :hotel
belongs_to :room
end
class Room < ApplicationRecord
belongs_to :room_category
has_many :reservations, dependent: :destroy
accepts_nested_attributes_for :room_category
end
class Hotel < ApplicationRecord
has_many :room_categories, dependent: :destroy
has_many :rooms, through: :room_categories
has_many :reservations, dependent: :destroy
end
class RoomCategory < ApplicationRecord
belongs_to :hotel
has_many :rooms, dependent: :destroy
accepts_nested_attributes_for :rooms, allow_destroy: true
end
hotel
is in Reservation
, not in Room
, so you have to:
Room.joins(:reservations).where(reservations: { hotel: hotel })
The :reservations
in where
is the table name, not the association name, which in this case is the same.
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.