提问人:Faisal 提问时间:9/12/2023 最后编辑:Faisal 更新时间:11/15/2023 访问量:136
has_many .build 关联 .build 没有在 DB for Rails 6.1 中保存对象
has_many association .build is not saving object in DB for Rails 6.1
问:
我正在升级到 Rails 6.1,并且在我的模型中具有以下关联
class Product < ApplicationRecord
has_many :classifications, dependent: :destroy
has_many :order_lines, dependent: :destroy
end
对于以下代码片段:
p = Product.new
p.classifications.build name: 'my name'
p.order_lines.build line_number: '123'
p.save
如果我在现有的代码环境(Rails 6.0、Ruby 2.7.7)中运行它,它会按预期工作。但是,如果我针对 Rails 6.1 运行它,则对象将存储在数据库中,而 将被丢弃。没有 SQL 语句尝试将其写入数据库,并且在保存后检查,返回一个空的 .
更改我们构建对象的顺序没有影响。更改模型中定义关联的顺序确实会更改行为(持久化,但未保留)classifications
order_line
p.order_lines.inspect
CollectionProxy
order_line
classifications
有趣的是,如果我切换到
p = Product.create # instead of .new
# rest of snippet
它在 Rails 6.1 上按预期工作,并且两者都被存储。这是非常令人困惑的行为,我不知道是什么引入了它。有什么想法吗?order_line
classification
编辑:该行为与我在任何模型上定义的任意两个关联一致。模型中首先定义的关联将被保存,而另一个关联将被删除。我尝试交换它们并重新加载我的控制台,保存与丢弃的控制台被交换了。has_many
答: 暂无答案
评论
p.order_lines.build line_number: '123'
build
new
p.order_lines.errors.full_messages
Product.new
Product.create
bin/rails _6.1.0_ new myapp
rails v6.0.0
rails v6.1.0