美文网首页
Rails: Polymorphic Association

Rails: Polymorphic Association

作者: bookinstock_ | 来源:发表于2017-04-27 21:52 被阅读98次

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

      本文链接:https://www.haomeiwen.com/subject/cninzttx.html