ruby-on-rails - 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
.
解决方案
这是内存中的对象未自动与数据库同步的问题。之后可以看到预期的结果:
pry(main)> batch.reload
pry(main)> batch2.reload
推荐阅读
- android - [amadeus] 调用 hotelOffers.get api 时出现异常
- c - C 中的文件操作 - 从 C 中的文件中删除特定行
- r - 根据另一列中的条件删除重复行
- python - 使用给定的 X 和 Y 值创建直方图
- postgresql - Flask-SqlAlchemy、Bcrypt、Postgres 的编码问题
- angular - 在我对表执行诸如添加/编辑/删除一行(Angular 10)之类的操作后,分页不起作用
- git - Git克隆:致命:无法访问'https://github.com/google-coral/pycoral.git/':服务器证书验证失败。CAfile:无 CRLfile:无
- java - 用于读取 csv 并指定超过 1 个字符(字符串)“|%|”的自定义分隔符的 Java 库
- visual-studio-code - 如何跟踪在 VSCode 中运行的冲突 linter
- html - CSS表格 - 第一行和第一列粘性