Rails 加入 table 与 record_type 和 recored_id 就像 activestorage

Rails join table with record_type and recored_id like activestorage

create_table :posts do |t|
  t.string   :title
  t.string   :content
end

create_table :post2s do |t|
  t.string   :title
  t.string   :content
end

create_table :users do |t|
  t.string   :email
  t.string   :name
end

create_table :likes do |t|
  t.references :users
  t.string :record_type
  t.integer :record_id
end

enter image description here

我想加入 table 喜欢 Activestorage record_type 和 record_id

谁能知道这个连接名称或站点如何创建这种连接样式?

看来你需要 polymorphic association

因此,正如您所描述的,您将拥有您喜欢的类型和 ID table。您的 posts 和 post2s 模型会将自己标识为多态类型。

例如帖子模型:has_many :likes, as: :likeable 和喜欢的模型:belongs_to :likeable, polymorphic: true

但请务必阅读指南。