如何在不删除记录的情况下取消记录与活动记录关联的关联?

时间:2015-07-08 15:35:13

标签: ruby-on-rails postgresql activerecord

如何在不删除记录的情况下取消关联记录?

考虑以下情况,Game有很多rulesrule有很多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的情况下更新关系。

2 个答案:

答案 0 :(得分:1)

game.rules.delete(Rule.find(2))

game.rule_ids = [1]
game.save

答案 1 :(得分:0)

在 Rails 6.1 中,我重写了 _delete_row 方法来搜索正确的列。适用于删除和销毁。

关系.ruby
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