我阅读了一些相关问题并尝试与has_many建立关系:通过+ 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
虽然这会返回nil。
Item.first.authors
我找不到错误。请帮帮我!
答案 0 :(得分:0)
我认为应该更明确地定义:
has_many :items, :through => :authorships, :source => :item, :conditions => "authorships.target_type = 'Item'"