"belongs to" 和 "has many" 通过?

"belongs to" and "has many" through?

这是我想要实现的目标:

我有 2 个模型 CategoryCollection

我想要这个协会:

Category 属于 Collection

Collection 有很多 Category

但我只需要为一些记录建立关联。像 100。 所以我看不出有任何理由为其余 100 000 条记录创建参考列。

我试过了,但没有成功:

class Category
  has_many :category_collection

  # This is not a valid option
  belongs_to :collection, through: :category_collection

  # And this will throw
  has_one :collection, through: :category_collection

  # ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have
  # a has_one :through association 'Category#collection'
  # where the :through association 'Category#category_collection' is
  # a collection. Specify a has_one or belongs_to association 
  # in the :through option instead.
end

class Collection
  has_many :category_collection
  has_many :categories, through: :category_collection
end

class CategoryCollection
  self.table_name = 'categories_collections'
  belongs_to :category
  belongs_to :collection
end

或者整个想法是错误的,我应该坚持使用无用的专栏?

Category 属于 Collection 意味着 Category 模型引用了 Collectioncollection_id 字段)。所以如果没有 99k 无用的记录,你就做不到。

但是可以改为定义 has_one 关联。

class Category
  has_one :category_collection 
  has_one :collection, through: :category_collection
end

好吧,我想说这有点脏,但你可能会像这样设置它。如果这完全是疯了,请告诉我。

class Category < ActiveRecord::Base
  has_one :category_collection
  has_one :collection, through: :category_collection
end

class Collection < ActiveRecord::Base
  has_many :category_collections
  has_many :categories, through: :category_collections
end

class CategoryCollection < ActiveRecord::Base
  self.table_name = 'categories_collections'
  belongs_to :category
  belongs_to :collection

  validate :only_one_category

  def only_one_category
    if CategoryCollection.all.pluck(:category_id).include?(category.id)
      errors.add(:category, "can only have one collection")
    end
  end
end

验证将确保您不能将多个集合添加到一个类别。