[P]olymorphic associations…can belong to more than one other model, on a single association. Ruby On Rails Guide http://guides.rubyonrails.org/ association_basics.html#polymorphic-associations
frees us from tightly coupling models together (:foo_id not a required attribute for :belongs_to) DRY ‣Rails provides us with concise solutions for variable model associations. Don’t Repeat Yourself
toffee, dark chocolate and a hint of wasabi A light, Italian shortbread with a taste of anise and a maple glaze Vienna-style finger cookies with a vanilla cream-cheese frosting (Vanilla, Lemon or Strawberry)
recipes are open source; we keep track of which chefs make which goodies ‣ We package our goodies in: ‣ Bags - 5 count ‣ Gift Boxes - 10 count ‣ Rail Cars - 20 count CANDY ON RAILS - POLYMORPHISM AND RAILS 5
GiftBox < ApplicationRecord belongs_to :address has_many :goodies end class RailCar < ApplicationRecord belongs_to :address has_many :goodies end class Address < ApplicationRecord has_many :bags has_many :gift_boxes has_many :rail_cars end class Goody < ApplicationRecord belongs_to :bags belongs_to :gift_box belongs_to :rail_car end Manually managed nils Each package requires an id Hard to scale
RAILS 5 THINGS TO CONSIDER ‣ Is your new model “sufficiently original”? ‣ Do you have to do decide now? ‣ What are the consequences of “vanilla” associations? ‣ What’s best for the user?
pertinent details of some of our goody types: CANDY ON RAILS - POLYMORPHISM AND RAILS 5 ‣ Taffy ‣ Salt water or Regular? ‣ Flavor ‣ Custom colors ‣ Cookies ‣ Vegan? ‣ Gluten-free? ‣ Allergies
so we can create another polymorphic relationship: CANDY ON RAILS - POLYMORPHISM AND RAILS 5 class Goody < ApplicationRecord belongs_to :package, polymorphic: true belongs_to :confection, polymorphic: true, optional: true end
< ApplicationRecord include GoodyPackageManager end class GiftBox < ApplicationRecord include GoodyPackageManager end class RailCar < ApplicationRecord include GoodyPackageManager end
‣ Polymorphism is a useful tool to manage complex associations ‣ Like any abstraction, it should be used sparingly ‣ Consider alternatives before implementing ‣ Remember the user