gpt4 book ai didi

ruby-on-rails - 多态关联中的一对多

转载 作者:行者123 更新时间:2023-12-04 03:44:31 24 4
gpt4 key购买 nike

基于我之前的 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:找不到关联:模型播放器中的帖子

有什么问题吗?

最佳答案

您可能可以取消这个中间的 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

关于ruby-on-rails - 多态关联中的一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20904918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com