情况:
我们有用户,曲目,列表等的图...以及所有这些模型都可以被标记并使用此标记进行过滤。
我想要做的是:
使用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
你可以使用has_many
协会:
日模型
class Tag < ApplicationRecord
has_many :relation
end
关系模型
class Relation < ApplicationRecord
belongs_to :tag
belongs_to :taggable, polymorphic: true
end
用户模型
class User < ApplicationRecord
has_many :relations, as: :taggable
has_many :tags, through: :relations
has_one :top_list
has_many :tracks, through: :top_list
end
跟踪模型
class Track < ApplicationRecord
has_many :relations, as: :taggable
has_many :tags, through: :relations
belongs_to :top_list
end
标签迁移
class CreateTags < ActiveRecord::Migration[5.2]
def change
create_table :tags do |t|
t.string :name
t.timestamps
end
create_table :relations, id: false do |t|
t.references :tags, index: true
t.references :taggable, polymorphic: true, index: true
end
end
end