简体   繁体   中英

polymorphic has_many :through relationships

I read some relevant questions and tried setting up relationships with has_many :through + polymorphic as below.

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

The migration file for "Authorship" is:

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

Added a data like below.

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

When I check the data, this works fine.

Author.first.items

While this returns nil.

Item.first.authors

I couldn't find an error. Please help me!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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