如何在不删除记录的情况下取消关联记录?
考虑以下情况,Game
有很多rules
而rule
有很多Games
所以
>> game.rules #=> [#<rule id: 1, ...>, #<rule id:2, ...>]
如何解除id {2}的规则与game
的关联而不删除它,所以关系最终会像这样:
>> game.rules #=> [#<rule id: 1, ...>]
我尝试将更新的数组重新分配给关系,但是这会阻止关联以某种方式保存将来的插入。我相信一个人无法将数组分配给关系。
这是我尝试过的:
>> tmp = game.rules.to_a
>> tmp.delete(rule_of_id2)
>> game.rules = tmp
^D
但是,未来的插入不会持续存在。
>> games.rules << new_rule_of_id3
^D
>> game.rules #=> [#<rule id: 1, ...>
它应该返回#=> [#<rule id: 1, ...>, #<rule id: 3, ...>]
如何在不明确删除rule
的情况下更新关系。
答案 0 :(得分:1)
game.rules.delete(Rule.find(2))
game.rule_ids = [1]
game.save
答案 1 :(得分:0)
在 Rails 6.1 中,我重写了 _delete_row
方法来搜索正确的列。适用于删除和销毁。
class Goal::Relationship < ApplicationRecord
belongs_to :parent, foreign_key: :parent_id, class_name: :Goal, inverse_of: :child_relationships
belongs_to :child, foreign_key: :child_id, class_name: :Goal, inverse_of: :parent_relationships
def _delete_row
self.class._delete_record({ parent_id: parent_id, child_id: child_id })
end
end
class Goal::RelationshipTest < ActiveSupport::TestCase
setup do
@parent = goals(:parent1)
end
test 'should delete a relationship' do
assert_difference -> { Goal::Relationship.count }, -1 do
@parent.child_relationships.first.delete
end
end
test 'should destroy relationships' do
assert_difference -> { Goal::Relationship.count }, -1 do
@parent.child_relationships.first.destroy
end
end
end