Emil Bonne Kristiansen
Emil Bonne Kristiansen

Reputation: 242

Rails: How to use includes with conditions?

I have a ressource Room that has_many reservations. Likewise the ressource Reservation belongs_to a room.

My reservation model has a starts_at and an ends_at attribute.

In my index action for the Room controller I want to get all the Rooms and include all the reservations for a certain date(the date is given as a parameter).

I have tried this code, but it doesn't seem to work as intended.

@rooms = Room.includes(:reservations).where("reservations.starts_at" => params[:date])

I am aware that this code does not take into account that a room could be reserved for multiple days, but I had to start somewhere.

SUM UP

Based on a date the action should return all the rooms, but only include the reservations that is relevant for that date.

EDIT

This is what I ended up doing.

controllers/rooms_controller.rb

def index
  @rooms = Room.includes(:reservations)
  @date = params[:date] ||= Date.today
end

views/rooms/index.html.haml

- @rooms.each do |room|
  - room.reservations.relevant(@date).each do |reservation|
    = reservation.id

models/reservation.rb

def self.relevant(date = Date.today)
  if date.blank?
    date = Date.today
  end
  where(
    '(starts_at BETWEEN ? AND ?) OR (ends_at BETWEEN ? AND ?)',
    date.to_date.beginning_of_day, date.to_date.end_of_day, 
    date.to_date.beginning_of_day, date.to_date.end_of_day
  )
end

It works alright, but the view is talking to the model I think?

Upvotes: 1

Views: 610

Answers (1)

mikej
mikej

Reputation: 66263

If your where conditions refer to another table then you also need to need to specify references as well as includes. e.g.

@rooms = Room.includes(:reservations).
    where("reservations.starts_at" => params[:date]).
    references(:reservations)

See the API documentation here.

Upvotes: 1

Related Questions