Rails 的多态关联

2015-10-27  本文已影响918人  迦南大人

首先很久没有写过 markdown, 真是不进则退,还好 google 了下,要感谢这篇文章 献给写作者的 Markdown 新手指南

多态关联的使用场景

多态关联的用法

以评论功能为例,Rails 里是这么做的,辞穷,直接上代码吧,非真实代码,我想象的。

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

class Post < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Image < ActiveRecord::Base
  has_many :comments, as: :commentable
end

我们需要一张 comments 表能关联 posts 表或 images 表

class CreateComments < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.integer :user_id
      t.text :content
      t.integer :commentable_id
      t.string  :commentable_type
      t.timestamps null: false
    end

    add_index :comments, :commentable_id
  end
end

基本奏是这样。然后就更正常的关联表一样使用就可以了,正常使用是怎么使用,可以参考这里 Polymorphic associations 。奏是这样。

上一篇 下一篇

猜你喜欢

热点阅读