On 2015-Apr-27, at 13:40 , Norm S. [email protected]
wrote:
I have an app running Rails 2.3 with Ruby 1.8.7. Upgrading is not in the
cards for a while.
I feel your pain.
containing a bunch of stuff about spaces
Norm
I think that this named_scope should work though I’m not sure that it
can be considered database agnostic. (Walter’s might be close, but not
until you have ARel to use.
Reservation.class_eval do
belongs_to :space
end
Space.class_eval do
has_many :reservations
named_scope :available_for, lambda{|start_dt, end_dt|
{ :conditions => [[“id NOT IN (SELECT space_id FROM reservations”,
“WHERE reservations.enddate > ?”,
“AND reservations.startdate < ?)”,
].join(" "), start_dt, end_dt] } }
end
Space.available_for(Date.new(2015,5,11), Date.new(2015,5,15))
The alternative would be to have a method on Reservation that returned
the space_ids:
Reservation.class_eval do
belongs_to :space
def self.for_space_ids_during(start_dt, end_dt)
find(:all, {
:conditions => [“enddate > ? AND startdate < ?”,
start_dt, end_dt],
:select => :space_id,
}).map(&:space_id)
end
end
Space.class_eval do
has_many :reservations
named_scope :except, lambda{|ids|
{ :conditions => [“id NOT IN (?)”,
Reservation.for_space_ids_during(start_dt,
end_dt)] } }
end
Or even making that an association extension:
Space.class_eval do
has_many :reservations do
def available_for(start_dt, end_dt)
reject {|rsv| rsv.enddate > start_dt && rsv.startdate < end_dt }
end
end
end
But this last bit is certainly the most inefficient and least visually
similar to what it sounds like you’d like to have in a modern version of
Rails.
In all cases, know that I haven’t run this code so I only suggest that
it might work.
-Rob