【问题标题】:polymorphic has_many :through relationships多态has_many:通过关系
【发布时间】:2012-03-27 09:20:07
【问题描述】:

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

我找不到错误。请帮帮我!

【问题讨论】:

    标签: ruby-on-rails-3 has-many-through has-many-polymorphs


    【解决方案1】:

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

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

    【讨论】:

    • 是否应该替换为“has_many :items, :through => :authorships, :source => :target, :source_type => 'Item'”?我试过这样做,但没有奏效。 “Author.first.items”也没有用。有什么想法吗?
    猜你喜欢
    • 2011-05-06
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多