Skip to content

Instantly share code, notes, and snippets.

@shilovk
Last active March 8, 2024 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shilovk/69af588fdc90672ff31398dae9d78a72 to your computer and use it in GitHub Desktop.
Save shilovk/69af588fdc90672ff31398dae9d78a72 to your computer and use it in GitHub Desktop.
For example: `locations` have many `trains`, `copters`, `trucks`, `ships`. And `trains`, `copters`, `trucks`, `ships` have many `locations`.
#db/migrations/create_moveable_locations.rb
class CreateMoveableLocations < ActiveRecord::Migration
def change
create_table :moveable_locations do |t|
t.references :moveable, polymorphic: true
t.references :location
t.timestamps
end
end
end
#app/models/moveable_location.rb
class MoveableLocation < ActiveRecord::Base
belongs_to :moveable, polymorphic: true
belongs_to :location
end
#app/models/location.rb
class Location < ActiveRecord::Base
has_many :moveable_locations, dependent: :destroy
has_many :trains, through: :moveable_locations, source: :moveable, source_type: 'Train'
has_many :copters, through: :moveable_locations, source: :moveable, source_type: 'Copter'
has_many :trucks, through: :moveable_locations, source: :moveable, source_type: 'Truck'
has_many :ships, through: :moveable_locations, source: :moveable, source_type: 'Ship'
end
#app/models/train.rb
class Train < ActiveRecord::Base
has_many :moveable_locations, as: :moveable, dependent: :destroy
has_many :locations, through: :moveable_locations
end
#app/models/copter.rb
class Copter < ActiveRecord::Base
has_many :moveable_locations, as: :moveable, dependent: :destroy
has_many :locations, through: :moveable_locations
end
#app/models/truck.rb
class Truck < ActiveRecord::Base
has_many :moveable_locations, as: :moveable, dependent: :destroy
has_many :locations, through: :moveable_locations
end
#app/models/ship.rb
class Ship < ActiveRecord::Base
has_many :moveable_locations, as: :moveable, dependent: :destroy
has_many :locations, through: :moveable_locations
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment