Neo4j gem - Updating relationship properties method

372 views Asked by At

This is a fairly simple question.

Is there a specific method for updating properties for relationships in the gem? I can't seem to do a simple update_attributes or update.

My relationship is created and update is undefined for nil class.

event = Event.find(params[:event]) 
invite = Invite.create_invitation(event, current_user, nil) #creates relationship
invite.update(interested: params[:interest])

Is there another method that I should be using?

1

There are 1 answers

2
subvertallchris On BEST ANSWER

Whenever you get an error about undefined for nil class, it should be an immediate signal to you that the problem is the variable on which you're calling the method, not the method you're calling. In other words, since it's saying that nil does not have an update method, your focus should be on the variable that is actually nil. The question here: why is invite returning nil instead of a relationship?

Since you're using a custom class method to create the relationship, I'm guessing that you're not telling it to return the right object. It should look something like this:

def self.create_invitation(event, user, something_else = nil)
  rel = InvitationRel.new(from_node: event, to_node: user)
  if rel.save
    rel
  else
    # return an error, maybe rel.errors.full_messages?
  end
end

Then your controller needs to check that the rel was actually created correctly.

event = Event.find(params[:event]) 
invite = Invite.create_invitation(event, current_user, nil) #creates relationship
if invite.neo_id.nil?
  # the rel did not create correctly, neo_id is only present on persisted objects
else
  invite.update(interested: params[:interest])
end

This feels to me like you're taking a long way around this problem. You don't need to separate the creation of the relationship and setting the interested property, you can just do it in one call to the DB:

event = Event.find(params[:event])
invite = InviteRel.new(from_node: event, to_node: current_user, interested: params[:interest])
if invite.save?
  # rel was created, move on
else
  # something wrong in the rel, figure out what it was
end

Since you know you're always going to create that interested property, this looks like a good place to add a validation to your model to ensure that the property is always set on create.