Rails中的单表继承与多态关联

单表继承,顾名思义,只有一张表,这张表对应一个类,这个类被其他类继承。

在数据库建模时,多个模型非常相似,为了避免创建多个相似的表,我们就可以使用单表继承的做法。

举个栗子,比如进销存系统中,有供应商和客户的概念,他们的很多属性都是相似的,我们可以只创建一张表companies,对应的类就是Company,而供应商类Supplier和客户类Customer都继承自Company。

class Company < ApplicationRecordendclass Supplier < Companyendclass Customer < Companyend

Rails实现这种单表继承,需要在companies表中包含type字段,在companies的数据库迁移文件中添加。

class CreateCompanies < ActiveRecord::Migration[7.0]  def change    create_table :companies do |t|      t.string :type      # ...other field    end  endend


多态关联,重点是关联二字,说的是1个表关联其他多个表。

举个栗子,一个网站内容丰富,有视频,有文章,那网友会留下对作品的评论。这个就涉及到评论表comments,视频表videos,文章表articles,只要我们做到这个评论表可以关联视频表,又关联了文章表,就实现了多态关联。

Rails实现多态关联,关键字是polymorphic,需要在Comment类中声明多态,在Video类和Article类中也做声明才行,具体看代码:

class Comment < ApplicationRecord  belongs_to :commentable, polymorphic: trueendclass Video < ApplicationRecord  has_many :comments, as: :commentableendclass Article < ApplicationRecord  has_many :comments, as: :commentableend

另外在comments表的数据库迁移文件中,还要给到2个字段,commentable_id 和 commentable_type:

class CreateComments < ApplicationRecord::Migration[7.0]  def change    t.references :commentable, polymorphic: true    # ...other fields  endend

这里的references写法是简写,它会对应生成commentable_id和commentable_type两个字段,而且还会添加对应的这2个字段的联合索引。

你学到了吗?

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章