Advertisement
paranoic

Correct polymorphic many-to-many associations

Jan 11th, 2014
834
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 1.50 KB | None | 0 0
  1. #Correct polymorphic many-to-many associations
  2.  
  3. #app/models/concerns
  4.  
  5. module Concerns
  6.   module Moveable
  7.     extend ActiveSupport::Concern
  8.    
  9.     included do
  10.       has_many :moveable_locations, as: :moveable, dependent: :destroy
  11.       has_many :locations, through: :moveable_locations      
  12.     end
  13.   end
  14. end
  15.  
  16. #app/models/train.rb
  17.  
  18. class Train < ActiveRecord::Base
  19.   include Concerns::Moveable
  20. end
  21.  
  22. #app/models/copter.rb
  23.  
  24. class Copter < ActiveRecord::Base
  25.   include Concerns::Moveable
  26. end
  27.  
  28. #app/models/truck.rb
  29.  
  30. class Truck < ActiveRecord::Base
  31.   include Concerns::Moveable
  32. end
  33.  
  34. #app/models/ship.rb
  35.  
  36. class Ship < ActiveRecord::Base
  37.   include Concerns::Moveable
  38. end
  39.  
  40. #db/migrations/create_moveable_locations.rb
  41.  
  42. class CreateMoveableLocations < ActiveRecord::Migration
  43.   def change
  44.     create_table :moveable_locations do |t|
  45.       t.references :moveable, polymorphic: true
  46.       t.references :location
  47.       t.timestamps
  48.     end
  49.   end
  50. end
  51.  
  52. #app/models/moveable_location.rb
  53.  
  54. class MoveableLocation < ActiveRecord::Base
  55.   belongs_to :moveable, polymorphic: true
  56.   belongs_to :location
  57. end
  58.  
  59. #app/models/location.rb
  60.  
  61. class Location < ActiveRecord::Base
  62.   has_many :moveable_locations, dependent: :destroy
  63.  
  64.   with_options :through => :moveable_locations, :source => :moveable do |location|
  65.     has_many :trains, source_type: 'Train'
  66.     has_many :copters, source_type: 'Copter'
  67.     has_many :trucks, source_type: 'Truck'
  68.     has_many :ships, source_type: 'Ship'
  69.   end
  70. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement