Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Correct polymorphic many-to-many associations
- #app/models/concerns
- module Concerns
- module Moveable
- extend ActiveSupport::Concern
- included do
- has_many :moveable_locations, as: :moveable, dependent: :destroy
- has_many :locations, through: :moveable_locations
- end
- end
- end
- #app/models/train.rb
- class Train < ActiveRecord::Base
- include Concerns::Moveable
- end
- #app/models/copter.rb
- class Copter < ActiveRecord::Base
- include Concerns::Moveable
- end
- #app/models/truck.rb
- class Truck < ActiveRecord::Base
- include Concerns::Moveable
- end
- #app/models/ship.rb
- class Ship < ActiveRecord::Base
- include Concerns::Moveable
- end
- #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
- with_options :through => :moveable_locations, :source => :moveable do |location|
- has_many :trains, source_type: 'Train'
- has_many :copters, source_type: 'Copter'
- has_many :trucks, source_type: 'Truck'
- has_many :ships, source_type: 'Ship'
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement