问题描述
我有一个带有 accepts_nested_attributes_for
的记录,创建后我想获取所创建记录的 ID 和属性而无需再次查询。可能吗?
例如,我有这样的记录:
class Product
has_many :variants
accepts_nested_attributes_for :variants
end
然后我可以这样做:
product = Product.create!(name: 'test_product',variants_attributes: [{ name: 'test_variant' }])
但是如果我调用 product.variants
,它会再次查询数据库。
解决方法
你的班级不应该是这样的:
class Product
has_many :variants
accepts_nested_attributes_for :variants
end
如果没有正确定义 accepts_nested_attributes_for
,我不确定您的代码是如何工作的。如果您已将创建的对象保存在变量 product.variants
中,product
命令不应触发另一个查询。