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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,420评论 0 23
  • 01 小树林里隐约传来一个呻吟的女声。 一辆汽车停在黑暗中,车上有一对激情的男女。 突然,黑暗中闪出一丝光亮,一阵...
    幸美人阅读 4,149评论 0 1
  • 我钦佩一种人,眉目间传递出最珍贵的表情是淡定、从容,一双眼睛流露出只有心灵宁静才能感受到的幸福,我愿自己成为这样的人。
    心源宝贝阅读 936评论 0 0
  • 旅途漫漫,本意想让自己能静静的放空下内心,调整下即将要进入的毕业季的学习状态,无奈天生享受不了孤独,特别是在这种人...
    夏小喵喵阅读 2,454评论 0 1
  • 只有永远的冷淡才是永远的亲密
    暹罗小可爱阅读 689评论 0 0