首页 > 解决方案 > Object is not removed from association even after foreign key is modified

问题描述

I have two models:

class Batch < ApplicationRecord
  has_many :transfers, dependent: :destroy
end

class Transfer < ApplicationRecord
  belongs_to :batch
end

I created one Batch with 2 transfers through a factory:

pry(main)> batch = FactoryBot.create(:batch_with_txs, tx_count: 2)
=>  #<Batch:0x000055d25d6c81f0 id: 4>

pry(main)> batch.iso20022_transfers                               
=> [#<Transfer:0x000055d25899e780
  id: 11,
  batch_id: 4>,
 #<Transfer:0x000055d25899da38
  id: 12,
  batch_id: 4>]

I want to create a second batch and move one transfer from the first batch to the second:

pry(main)> batch2 = FactoryBot.create(:batch)
=> #<Batch:0x000055d25cc291b8 id: 5>

pry(main)> tx = Transfer.find(11)
(…)
pry(main)> tx.batch = batch2
(…)
pry(main)> tx.save
=> true

But if I check batch.transfers or batch2.transfers, the transfer is still present in batch and absent in batch2.

标签: ruby-on-railsrails-activerecord

解决方案


这是内存中的对象未自动与数据库同步的问题。之后可以看到预期的结果:

pry(main)> batch.reload
pry(main)> batch2.reload

推荐阅读