полиморфный has_many: через отношения - PullRequest
0 голосов
/ 27 марта 2012

Я прочитал некоторые важные вопросы и попытался установить отношения с 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

Я не смог найти ошибку. Пожалуйста, помогите мне!

1 Ответ

0 голосов
/ 27 марта 2012

Я думаю, это должно быть определено так:

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