2009-05-27 43 views
0

鉴于下面定义的关联,我希望有人可以阐明为什么我不能访问属于类别的所有分类,为什么我不能访问属于分类的所有分类。 我猜它与这里有一个多态关系 这个事实有关,但我想知道是否有正确的方法来做我想要的只用 关联语句,或者如果我有“滚动我自己的”,并获得 分两个阶段。has_many:through via secondary polymorphism

也许更容易只看到代码来理解:

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. 

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

任何意见或建议将不胜感激。提前致谢。

真诚, 肯尼

回答

0

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

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

可能想看看这个railscast

+0

遗憾的是,由于没有foreign_key返回到分类中的CategorySection,因此不起作用。你可以用另一种方式,一个分类可以找出它在哪个类别,然后得到它的CategorySection,但不是我想要的方式。 – kennyc 2009-05-28 00:08:54

0

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

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

,但我不知道这是否允许做双:在单独的模型通过(像你这样)。首先,你可以尝试没有多态的做 - 如果它有效,那么我的建议是错误的。

我认为Rails试图为您的所有关联链生成单个SQL查询 - 而且这非常复杂。

当然,您可以编写自己的:finder_sql该关联。