Created
April 22, 2011 00:44
-
-
Save superlou/935790 to your computer and use it in GitHub Desktop.
Modeling polymorphic has_many :through
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A user creates Spaces (rooms), Items (things), and Profiles (people). | |
Reservations are used to schedule times when these three models are in use and cannot be used elsewhere. | |
Since the modeling of a thing that can only be in use in one place/activity is common to Spaces, Items, and Profiles, this common functionality makes up the polymorphic model Resource. | |
Reservation | |
belongs_to :manager, :class_name => "Profile" | |
has_many :reservation_lines, :before_add => :set_nest, :dependent => :destroy | |
has_many :profiles, :through => :reservation_lines, :source => :reservable, :source_type => 'Profile' | |
has_many :spaces, :through => :reservation_lines, :source => :reservable, :source_type => 'Space' | |
has_many :items, :through => :reservation_lines, :source => :reservable, :source_type => 'Item' | |
accepts_nested_attributes_for :reservation_lines, :allow_destroy => true, | |
:reject_if => proc {|attributes| attributes['reservable_id'].blank?} | |
ReservationLine | |
belongs_to :reservation | |
belongs_to :reservable, :polymorphic => true | |
Profile | |
include ReservableMixin | |
Space | |
include ReservableMixin | |
Item | |
include ReservableMixin | |
module ReservableMixin | |
def self.included(base) | |
base.has_many :reservation_lines, :as => :reservable | |
base.has_many :reservations, :through => :reservation_lines | |
end | |
def reservations_overlapping(range) | |
overlapping = reservations.select {|r| r.range.overlap?(range)} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm new to this, so take this with a grain of salt. Good luck railsing!