Ruby on rails 集合关联帮助程序用于创建模型记录时失败

Ruby on rails 集合关联帮助程序用于创建模型记录时失败,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,我设置了rails模型,这样一个玩家可以关联到许多俱乐部s,而俱乐部可以关联到许多玩家s 这些模型通过一个名为PlayerClub的连接记录联系在一起,有许多:通过关联 class Player < ApplicationRecord has_many :player_clubs, dependent: :destroy has_many :clubs, through: :player_clubs accepts_nested_attributes_for :clubs, a

我设置了rails模型,这样一个
玩家可以关联到许多
俱乐部
s,而
俱乐部
可以关联到许多
玩家
s

这些模型通过一个名为
PlayerClub
的连接记录联系在一起,
有许多:通过
关联

class Player < ApplicationRecord
  has_many :player_clubs, dependent: :destroy
  has_many :clubs, through: :player_clubs
  accepts_nested_attributes_for :clubs, allow_destroy: true
end

class Club < ApplicationRecord
  has_many :player_clubs, dependent: :destroy
  has_many :players, through: :player_clubs
  accepts_nested_attributes_for :players, allow_destroy: true
end

class PlayerClub < ApplicationRecord
  belongs_to :player
  belongs_to :club

  validates :player, presence: true
  validates :club, presence: true
end
虽然上述操作适用于
更新
,但不适用于初始化:

> @player = Player.new({ name: "Foo", club_ids: [1,2,3] })

ActiveRecord::RecordNotFound: Couldn't find Player without an ID
from /Users/jeeves/.rvm/gems/ruby-2.5.5/gems/activerecord-6.0.0/lib/active_record/relation/finder_methods.rb:423:in `find_with_ids'
它感觉像是
club#u id=
应该像其他属性编写器一样工作,但它首先需要一个
Player#id
,这样它就可以在加入记录上设置
PlayerClub#Player#u id

这是故意的行为吗?有什么好办法吗


谢谢

我尝试在这里重新创建它,但无法得到相同的异常。当你建立关系时,你是否有可能在寻找球员的回电?如果俱乐部不存在,我唯一能做的就是重新创建一个例外。
> @player = Player.new({ name: "Foo", club_ids: [1,2,3] })

ActiveRecord::RecordNotFound: Couldn't find Player without an ID
from /Users/jeeves/.rvm/gems/ruby-2.5.5/gems/activerecord-6.0.0/lib/active_record/relation/finder_methods.rb:423:in `find_with_ids'