Advertisement
paranoic

Incorrect optimal many-to-many associations

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