class Location < ActiveRecord::Base has_many :opening_hours, :order => :day_of_week, :dependent => :destroy def hours out = HoursForLocation.new for i in 0..6 do out[i] = opening_hours.find :first, :conditions => "day_of_week = #{i}" end out end def hours=(hours) hours.each do |day,values| self.create_or_update_opening_hours(day, values) end end def closed=(days) hours = OpeningHour.find :all, :conditions => "location_id = #{self.id} AND day_of_week IN (#{days.keys.join(',')})" hours.each{|h| h.update_attribute(:closed, true)} end def create_or_update_opening_hours(day, values) values.symbolize_keys! hour = opening_hours.find :first, :conditions => "day_of_week = #{day}" hour ||= OpeningHour.new :location => self, :day_of_week => day hour.open, hour.close = values[:open], values[:close] hour.save end end class HoursForLocation < Array end