繁体   English   中英

多态has_many:通过关系

[英]polymorphic has_many :through relationships

我阅读了一些相关的问题,并尝试与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

虽然返回nil。

Item.first.authors

我找不到错误。 请帮我!

我认为应该更像这样定义:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM