I have this problem with records that have to be alligned on end- and
startdate. I came up with the following. but am not convinced that this
is the best way to tackle this problem. Anyone care for a braindump?
def head_to_tail
# Remove days that have startdate >= self.startdate AND enddate <=
self.enddate
#
# before after
#
# |=====| |=====|
# <----|--|----> <---| |---->
#
#
@days_inside_new_day = Day.find(:all, :conditions => [ "id != ? and
child_id = ? and startdate >= ? and enddate <= ?", self.id,
self.child_id, self.startdate, self.enddate])
@days_inside_new_day.collect {|d| d.destroy}
# Split days that have startdate <= self.startdate and enddate >=
self.enddate
#
# before after
# |==|
# |---------| |---|==|--|
#
@day1 = Day.find(:all, :conditions => [ "id != ? and child_id = ?
and startdate <= ? and enddate >= ?", self.id, self.child_id,
self.startdate, self.enddate])[0]
if (@day1)
@day2 = @day1.clone
if (@day1.startdate < self.startdate)
@day1.enddate = self.startdate - 1
@day1.save
else
# day1 and self start on the same day, destroy day1.
#
# before after
# |==|
# |---------| |==|------|
#
@day1.destroy
end
@day2.startdate = self.enddate + 1
@day2.save
end
# Find all records that belong to the same Child, and order them on
startdate (most recent startdate first) and then on enddate (most recent
enddate first)
@days = Day.find(:all, :conditions => [ "child_id = ?",
self.child_id], :order => "startdate DESC, enddate DESC")
@lastday = @days.shift
for @day in @days
if (@lastday.startdate > @day.startdate and @lastday.startdate <
@day.enddate)
# start of lastday between start and end of day
if (@lastday == self) # Don''t modify self!
#
# before after
# |====>
# |------|---> |---|====>
#
@day.enddate = @lastday.startdate - 1
@day.save
else
#
# before after
# |---->
# |======|---> |======|-->
#
@lastday.startdate = @day.enddate + 1
@lastday.save
end
end
if (@lastday.startdate > @day.enddate)
# start of lastday after end of day
if (@lastday == self) # Don''t modify self!
#
# before after
# |==>
# |---| |-----|==>
#
@day.enddate = @lastday.startdate - 1
@day.save
else
#
# before after
# |-->
# |===| |===|--->
#
@lastday.startdate = @day.enddate + 1
@lastday.save
end
end
@lastday = @day
end
end
--
Posted via http://www.ruby-forum.com/.