Search code examples
ruby-on-railsneo4jdestroyneo4j.rb

Neo4j gem - Effecient ways to destroy associated nodes and relationships


I know that the gem doesn't have a built in way to handle dependency destroys yet like active rececord dependant: destroy

Is there better ways to deal with chain destroying?

For example, right now I am trying to deal with destroying with my Q+A

Each question has many answers and each answer has one question

Destroying the question can be done like so

event_question = EventQuestion.find(params[:id])

event_question.destroy

but if I need to deal with the answers, and I do it through this association, I have to loop through and destroy each one. An added weakness is needing to check if the dependent nodes/relationships even exist.

Is it better to write out a longer query to deal with finding both the questions and answers and destroying them in one swoop? (or... can you?) I know you can't destroy the queryproxy like so (e.g. event_question.answers.destroy)

UPDATE

I've tried to implement these two queries with delete but delete doesn't execute. No error message right now. Prying into the method, the matches look right.

event.users(:u,:rel).query.match("()-[r3]-u").delete(:r3).exec
event.event_questions(:q).event_answers(:a).query.match("event-[r0]-(), q-[r1]-(), a-[r2]-()").delete(:q, :a, :event).exec

UPDATE 2

This is the cypher query for the first event.users.

MATCH (event13:`Event`), (u:`User`), event13-[rel:`invited`]-(u:`User`), ()-[r3]-u WHERE ID(event13) = {ID_event13} DELETE r3"

It looks right? But delete doesn't seem to execute. Attaching as or query_as doesn't allow the query to go through on the second one. It gives me undefined method as

LAST UPDATE

Last update before moving to a different question.

Oddly, I can get the first query to delete the relationship via this

event.users(:u,:r3).query.match("()-[r]-u").delete(:r3).exec

but this next query won't delete the question and answers.

event.event_questions(:q).event_answers(:a).query.match("q-[r1]-(), a-[r2]-()").delete(:q, :a).exec

I'm not entirely sure why the match is needed but without it, it doesn't execute either. When I wrote my destroy functions on my Questions/Answers controller, I didn't actually have to delete the relationship. But maybe I did something funky.

I actually did this

answers = event_question.event_answers

and then looped it and destroyed each answer, which seemed to destroy both answer and the relationship with the question. The Q+A are set up through associations and not ActiveRel.. not sure if that makes a difference.


Solution

  • Chris and company is working on a PR for the dependent destroy ability. It seems to work on master branch of the gem currently. It seems to do the job a -ok!

    https://github.com/neo4jrb/neo4j/pull/653