我正在关注本教程,该教程在 has_many :through 关系中表现出色。我有正常的事情,比如 category_product 工作。
但是,我无法将这种情况概念化(也无法使其发挥作用):我有一个具有相关类别的类别。由于每个类别都可以有 N 个类别……首先,这实际上是多对多的情况吗(我很肯定它是)?其次,这会是什么样子?我的迁移如下所示:
create_table :categories do |t|
t.string :name
t.timestamps
end
create_table :related_categories, :id => false do |t|
t.integer :category_a_id
t.integer :category_b_id
end
我的模特的胆量是
has_many :related_categories, :foreign_key=>"category_a_id"
has_many :categories, :through => :related_categories, :source=>:category_a
这显然是不对的,尽管它已经到达那里(即,它已 100% 损坏)。我怎样才能做到这一点?
编辑:我忘记了这一点,但只在这里(意思是这不是答案):
class RelatedCategory < ActiveRecord::Base
belongs_to :category_a, :class_name=>"Category"
belongs_to :category_b, :class_name=>"Category"
end