has_many:通过二次多态性

时间:2009-05-27 19:45:40

标签: ruby-on-rails

考虑到下面定义的关联,我希望有人可以解释为什么我不能 访问属于某个类别的所有分类,而这些分类又属于某个部分。 我猜这与有多态关系这一事实有关 在那里,但我想知道是否有一种正确的方法来做我想要的东西 协会声明,或者如果我必须“滚动我自己的”并获得分类广告 两个阶段。

通过查看代码可能更容易理解:

class CategorySection < ActiveRecord::Base
  has_many :categories
  has_many :categorizations, :through => :categories
  has_many :classifieds, :through => :categories
end

class Category < ActiveRecord::Base
  belongs_to :section, :class_name => 'CategorySection', 
                       :foreign_key => 'category_section_id', 
                       :counter_cache => true
  has_many :categorizations
  has_many :classifieds, :through => :categorizations, 
                         :source => :categorizable, 
                         :source_type => 'Classified'
end

class Categorization < ActiveRecord::Base
  belongs_to :category, :counter_cache => true
  belongs_to :categorizable, :polymorphic => true
end

class Classified < ActiveRecord::Base
  has_one :categorization, :as => :categorizable, :dependent => :destroy
  has_one :category, :through => :categorization
end

在大多数情况下,这一切都正常,除了一个我无法弄清楚的关联。 给定一个CategorySection,我怎样才能快速找到属于它的所有分类?

例如:

鉴于一个类别,我可以得到它的所有分类:

>> @category.categorizations
>> [<Categorization...>,<Categorization...>]

鉴于一个类别,我可以获得其中的所有分类:

>> @category.classifieds
>> [<Classified...>,<Classified...>]

给定一个部分,我可以获得所有类别:

>> @section.categories
>> [<Category...>,<Category...>]

给定一个部分,我可以完成所有的分类:类别

>> @section.categorizations
>> [<Categorization...>,<Categorization...>]

但是,鉴于一个部分,我无法完成所有分类:类别

>> @section.classifieds
ActiveRecord::HasManyThroughSourceAssociationMacroError: 
Invalid source reflection macro :has_many :through for 
has_many :classifieds, :through => :categories. Use :source 
to specify the source reflection.

我已经收到错误消息的建议,指定一个:source,但我仍然无法让它工作。我已经尝试了几乎所有关于该关联的选项组合,但是无济于事。

任何建议或建议都将非常感谢。提前谢谢。

此致 肯尼

2 个答案:

答案 0 :(得分:0)

您是否尝试过定义没有“:through”的has_many?

class CategorySection < ActiveRecord::Base
  has_many :categories
  has_many :categorizations, :through => :categories
  has_many :classifieds
end

可能想看看这个railscast

答案 1 :(得分:0)

我记得Rails不允许使用:通过不止一次的关联。肯定你不能做这样的事情:

has_many :books
has_many :authors, :through => :books
has_many :phones, :through => :authors

但我不确定它是否允许双重:通过单独的模型(如你的)。首先,您可以尝试在没有多态的情况下进行 - 如果有效,那么我的建议是错误的。

我认为Rails正试图为你的所有协会链提供单一的SQL查询 - 而且它非常复杂。

您肯定可以编写自己的:finder_sql用于该关联。