多态关联中的一对多

时间:2014-01-03 13:37:05

标签: ruby-on-rails orm polymorphic-associations

基于我以前的question,我正在构建一个多态关联。我也希望有一对多的关系。所以我创建了一个新的表/模型posties / Posty来管理这种关系

帖子可以属于多个玩家和多个团队。

型号:

class Posty < ActiveRecord::Base
    belongs_to :posts
    belongs_to :target, :polymorphic => true
end

class Post < ActiveRecord::Base
    has_many :posties
    has_many :players, :through => :posties
end

class Player < ActiveRecord::Base
    has_many :posts,:as => :target, :through => :posties
end

表:

  create_table "posties", id: false, force: true do |t|
    t.integer  "posty_id"
    t.string   "posty_type", limit: 30
    t.integer  "post_id"
  end

  create_table "posts", force: true do |t|
    t.integer  "user_id"
    t.date     "post_date"
    t.string   "title"
  end

  create_table "players", force: true do |t|
    t.string   "name"
  end

当我这样做时,Player.find(1).posts,我得到了

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :posties in model Player

可能出现什么问题?

1 个答案:

答案 0 :(得分:3)

你可能可以取消这个中间Posty类,因为只需要连接表/模型来进行多对多关联。除此之外,你需要修复设置。

多态列名称应基于关联名称。

create_table "posties", force: true do |t|
  t.integer  "target_id"
  t.string   "target_type", limit: 30
  t.integer  "post_id"
end

class Posty < ActiveRecord::Base
  belongs_to :post
  belongs_to :target, :polymorphic => true
end

class Post < ActiveRecord::Base
  has_many :posties
  has_many :players, :through => :posties, :as => :target
end

class Player < ActiveRecord::Base
  has_many :posties, :as => :target
  has_many :posts, :through => :posties
end

编辑:

我最好补充一点,这可能仍然无效。我相当肯定你不能拥有has_many虽然是多态关联。在这种情况下,你应该删除Posty类,或者变得非常有创意!

create_table "posts" do |t|
  t.integer  "target_id"
  t.string   "target_type", limit: 30
end

class Post < ActiveRecord::Base
  belongs_to :target, :polymorphic => true
end

class Player < ActiveRecord::Base
  has_many :posts, :as => :target
end