Electromuis
Electromuis

Reputation: 3

Ruby on Rails, model method in where

I have a model room with has certain reservations for certain days. I have a method that returns if there are any reservations for a certain period. How can I get all the rooms without reservations for that period?

This is the code I have now, but when I use

@rooms = @category.rooms.availible(@date_start, @date_end), 

It returns all the rooms no matter what relations. And when I use

room.reservations.where("date_start >= ? || date_end <= ?", startd, endd).count 

It returns the amount just fine -.-

class Room < ActiveRecord::Base
  attr_accessible :cat_id, :room_nr
  validates_uniqueness_of :room_nr

  has_many :reservations
  belongs_to :category, foreign_key: "cat_id"

  def self.availible(startd, endd)
    where(self.Resvs(startd, endd)==0)
  end

  def self.Resvs(startd, endd)
    return joins(:reservations).where("date_start >= ? || date_end <= ?", startd, endd).count
  end
end

I moved the query to the controller for now, to get he rooms i use

@rooms = @category.rooms.joins('LEFT OUTER JOIN reservations ON reservations.room_id = rooms.id').where("date_start >= ? || date_end <= ?", @date_start, @date_end)

But that returns all the rooms that have a reservation, no matter what date (also the rooms need to come from their parent @category)


Getting close, changed it select the ones where reservation is off like this

    @rooms = @category.rooms.joins('LEFT OUTER JOIN reservations ON reservations.room_id = rooms.id').
                where("room_id IS NULL OR date_start > ? OR date_end < ?", @date_end, @date_start)

Works with one reservation but when i add more reservations on one room is doesn't work anymore

Upvotes: 0

Views: 178

Answers (2)

Electromuis
Electromuis

Reputation: 3

Fixed it! Thx for the help

def self.availible(startd, endd)
   where("NOT EXISTS(select 1 from reservations where reservations.room_id = rooms.id and ((date_start>=:date_start AND date_start<=:date_end) OR (date_end>=:date_start AND date_end<=:date_end)))", {date_start: startd, date_end: endd})
end 

Upvotes: 0

Yann VERY
Yann VERY

Reputation: 1819

In this case you can use NOT EXISTS like this :

def self.availible(startd, endd)
  @category.rooms.where("NOT EXISTS(select 1 from reservations where reservations.room_id = rooms.id and (date_start > ? OR date_end < ?))", startd, endd)
end 

Hope this helps

Upvotes: 0

Related Questions