【问题标题】:how do I disassociate a record from an activerecord association without deleting the record?如何在不删除记录的情况下解除记录与活动记录关联的关联?
【发布时间】:2015-09-26 15:17:28
【问题描述】:

如何在不删除记录的情况下解除记录与关联的关联?

考虑以下场景,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, ...>

它应该返回#=&gt; [#&lt;rule id: 1, ...&gt;, #&lt;rule id: 3, ...&gt;]

如何在不明确删除rule 的情况下更新关系。

【问题讨论】:

标签: ruby-on-rails postgresql activerecord


【解决方案1】:
game.rules.delete(Rule.find(2))

game.rule_ids = [1]
game.save

【讨论】:

    【解决方案2】:

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

    relationship.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
    

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      相关资源
      最近更新 更多