简体   繁体   English

多态has_and_belongs_to_many

[英]Polymorphic has_and_belongs_to_many

How define a has_and_belongs_to_many polymorphic association? 如何定义has_and_belongs_to_many多态关联?

Situation: 情况:

Figure that we have users, tracks, lists, etc... and all these models can be tagged and use this tag for filter. 如图所示,我们有用户,曲目,列表等...,所有这些模型都可以标记并使用此标记进行过滤。

What i'm trying to do is: 我想做的是:

Use has_and_belongs_to_many that enable to a tag to have other objects, and that other objects also can have other tags. 使用has_and_belongs_to_many可以使标签具有其他对象,并且其他对象也可以具有其他标签。

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. 因此,要启用属于一种以上对象(用户,轨道或轨道列表)的标签,我们需要使用多态关系。

That's my code on this moment: 这是我目前的代码:

tags migration 标签迁移

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

tag model 标签模型

class Tag < ApplicationRecord
  has_and_belongs_to_many :taggable, polymorphic: true
end

user model 用户模型

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

track model 轨道模型

class Track < ApplicationRecord
  has_and_belongs_to_many :tags, as: :taggable
  belongs_to :top_list
end

You can use a has_many association: 您可以使用has_many关联:

Tag model 标签模型

class Tag < ApplicationRecord
  has_many :relation
end

Relation model 关系模型

class Relation < ApplicationRecord
  belongs_to :tag
  belongs_to :taggable, polymorphic: true
end

User model 用户模型

class User < ApplicationRecord
  has_many :relations, as: :taggable
  has_many :tags, through: :relations

  has_one :top_list
  has_many :tracks, through: :top_list
end

Track model 轨道模型

class Track < ApplicationRecord
  has_many :relations, as: :taggable
  has_many :tags, through: :relations

  belongs_to :top_list
end

Tags migration 标签迁移

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM