多态has_many:通过关系

问题描述:

我读了一些相关的问题,并试图建立与has_many的关系:通过+多态如下。多态has_many:通过关系

class Item < ActiveRecord::Base 
    has_many :authorships, :as => :target 
    has_many :authors, :through => :authorships 
end 

class Author < ActiveRecord::Base 
    has_many :authorships 
    has_many :items, :through => :authorships, :source => :target, :source_type => 'Item' 
end 

class Authorship < ActiveRecord::Base 
    belongs_to :author 
    belongs_to :target, :polymorphic => true 
end 

为 “署名” 迁移文件是:

create_table :authorships do |t| 
    t.integer :author_id 
    t.string :target_type 
    t.integer :target_id 
    t.timestamps 
end 

添加像下方的数据。

a = Authorship.new 
a.target = @item 
a.author = @author 
a.save 

当我检查数据时,这工作正常。

Author.first.items 

虽然这返回nil。

Item.first.authors 

我找不到错误。请帮帮我!

我认为应该更多这样的定义:

has_many :items, :through => :authorships, :source => :item, :conditions => "authorships.target_type = 'Item'" 
+0

它应该通过“的has_many所取代:项目:通过=>:的著者,:源=>:目标:SOURCE_TYPE =>“项目““?我试图这样做,但它没有奏效。 “Author.first.items”也不起作用。有任何想法吗? – tomoto 2012-03-29 05:38:06