多态has_and_belongs_to_many [英] Polymorphic has_and_belongs_to_many
本文介绍了多态has_and_belongs_to_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
情况:
图中显示我们具有用户,曲目,列表等...,并且可以标记所有这些模型并将其用作过滤器.
我想做的是:
使用has_and_belongs_to_many
使标签具有其他对象,并且其他对象也可以具有其他标签.
Use has_and_belongs_to_many
that enable to a tag to have other objects, and that other objects also can have other tags.
因此,要启用属于一种以上对象(用户,轨道或轨道列表)的标签,我们需要使用多态关系.
So for enable a tag that belongs to more than one kind of object (users or tracks or tracklists), we need to use polymorphic relations.
这是我目前的代码:
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
这篇关于多态has_and_belongs_to_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文