开发者

How to remove a record without destroying it?

开发者 https://www.devze.com 2023-03-22 18:56 出处:网络
I am using Mongoid and I have 2 models, Flow and Node with a referenced parent-child relationship. class Node

I am using Mongoid and I have 2 models, Flow and Node with a referenced parent-child relationship.

class Node
  belongs_to :flow
end

class Flow
  has_many :nodes
end

When I want to remove a node with a flow I do this:

flow.nodes.clear

This destroy the associated nodes. What if I want to remove the association between the node and the flow without destroying the associated nodes? I开发者_JAVA百科s there a way of doing that?


You should be able to use flow.nodes.clear as long as you don't have :dependent => :destroy set. From the Rails Guide on Association Basics:

4.3.1.7 collection.clear

The collection.clear method removes every object from the collection. This destroys the associated objects if they are associated with :dependent => :destroy, deletes them directly from the database if :dependent => :delete_all, and otherwise sets their foreign keys to NULL.

If this isn't working for you, you could try this and it should remove the association:

flow.nodes = nil

EDIT 1

If not, you'll have to create a method to remove the association manually.

   flow.nodes.update_all :flow_id => nil


I don't believe there's any in built method for this, but you can do this:

Node.where(:flow_id => flow.id).update_all(:flow_id => nil)
0

精彩评论

暂无评论...
验证码 换一张
取 消