如何定义 has_and_belongs_to_many 多态关联?
情况:
想象一下我们有用户、曲目、列表等......并且所有这些模型都可以被标记并使用此标签进行过滤。
我想做的是:
Use has_and_belongs_to_many
这使得标签可以拥有其他对象,并且其他对象也可以拥有其他标签。
因此,为了启用属于多种对象(用户或曲目或曲目列表)的标签,我们需要使用多态关系。
这是我此刻的代码:
标签迁移
class CreateTags < ActiveRecord::Migration[5.2]
def change
create_table :tags do |t|
t.string :name
t.references :taggable, polymorphic: true, index: true
t.timestamps
end
create_table :assemblies_parts, id: false do |t|
t.belongs_to :assembly, index: true
t.belongs_to :part, index: true
end
end
end
标签模型
class Tag < ApplicationRecord
has_and_belongs_to_many :taggable, polymorphic: true
end
用户模型
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_and_belongs_to_many :tags, as: :taggable
has_one :top_list
has_many :tracks, through: :top_list
end
轨道模型
class Track < ApplicationRecord
has_and_belongs_to_many :tags, as: :taggable
belongs_to :top_list
end