【发布时间】:2018-11-29 08:30:07
【问题描述】:
我使用的是 Rails 5.1.6,但在 accept_nested_attributes_for 方面遇到问题。
我有两个模型
class Material < ApplicationRecord
belongs_to :rubric, optional: true
accepts_nested_attributes_for :rubric, allow_destroy: true
end
class Rubric < ApplicationRecord
has_many :materials, dependent: :nullify
end
我不知道如何破坏材料和规则之间的关系。
我有一个测试用例:
it 'should delete relation to rubric' do
# create two materials with relation to the same rubric
item = FactoryBot.create(:material_with_rubric)
expect(Rubric.count).to eq(1)
expect(item.rubric_id).to_not eq(nil)
FactoryBot.create(:material, rubric_id: item.rubric_id)
expect(Material.count).to eq(2)
# try to destroy relation for first material
item.assign_attributes(
rubric_attributes: {
id: item.rubric_id,
_destroy: '1'
}
)
# check
expect(item.valid?).to eq(true)
expect(item.save).to eq(true)
expect(item.rubric_id).to eq(nil)
# rubric should exist in database because we have second material with relation
expect(Rubric.count).to be > 0
end
但是,运行测试用例后我看到一个错误:
Failure/Error: expect(Rubric.count).to be > 0
expected: > 0
got: 0
如何使用 rubric_attributes 销毁关系并且不从数据库中删除项目。 例如,accepts_nested_attributes_for 和 allow_destroy 与 has_many 配合得很好
附:我知道 item.update(rubric_id: nil)。但我想使用 item.update(rubric_attributes: {})
获得相同的结果【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-5