Rails: Polymorphic Association

intro

  • a model can belong to more than one other models.
  • polymorphic belongs_to set up an interface that any other models can use.
    • e.g. Picture model belongs to imageable, Product model as imageable.
    • e.g. Reputation model belongs to reputable, User model as reputable.

basic example

  • rails generator
    • rails g picture imageable:references{polymorphic}
    • t.references :imageable, polymorphic: true
      • add columns: :imageable_id and :imageable_type
      • add index: t.index ["imageable_type", "imageable_id"]
  • models:
    • belongs_to :imageable, polymorphic: true # Picture
    • has_many :pictures, as: :imageable # User
    • has_many :pictures, as: :imageable # Product
  • rails console:
    • @user.pictures
    • @product.pictures
    • @picture.imageable

你可能感兴趣的:(Rails: Polymorphic Association)