我阅读了一些相关问题并尝试与 has_many :through + polymorphic 建立关系,如下所示。
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
虽然这返回零。
Item.first.authors
我找不到错误。请帮我!