多态has_and_belongs_to_many

问题描述 投票:0回答:1

如何定义has_and_belongs_to_many多态关联?

情况:

我们有用户,曲目,列表等的图...以及所有这些模型都可以被标记并使用此标记进行过滤。

我想要做的是:

使用has_and_belongs_to_many可以使标记具有其他对象,并且其他对象也可以具有其他标记。

因此,为了启用属于多种对象(用户或轨道或跟踪列表)的标签,我们需要使用多态关系。

那是我这个时刻的代码:

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
ruby-on-rails has-and-belongs-to-many polymorphic-associations
1个回答
0
投票

你可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.