2

I have a Jruby on Rails application with Neo4j.rb and a model, let's say Auth, defined like this:

class Auth < Neo4j::Rails::Model
  property :uid, :type => String, :index => :exact
  property :provider, :type => String, :index => :exact
  property :email, :type => String, :index => :exact
end

And this code:

a = Auth.find :uid => 324, :provider => 'twitter'
# a now represents a node
a.to_json
# outputs: {"auth":{"uid": "324", "provider": "twitter", "email": "email@example.com"}}

Notice that the ID of the node is missing from the JSON representation. I have a RESTful API within my application and I need the id to perform DELETE and UPDATE actions.

I tried this to see if it works:

a.to_json :only => [:id]

But it returns an empty JSON {}.

Is there any way I can get the ID of the node in the JSON representation without rewriting the whole to_json method?

Update The same problems applies also to the to_xml method.

Thank you!

Vlad V
  • 1,594
  • 1
  • 13
  • 28

2 Answers2

3

I am answering my own question. I still think that there is a better way to do this, but, for now, I am using the following hack:

In /config/initializers/neo4j_json_hack.rb I put the following code:

class Neo4j::Rails::Model
    def as_json(options={})
        repr = super options
        repr.merge! '_nodeId' => self.id if self.persisted?
    end
end

And now every JSON representations of my persisted Neo4j::Rails::Model objects have a _nodeId parameter.

Vlad V
  • 1,594
  • 1
  • 13
  • 28
  • 1
    I'm just getting started with neo4j and neo4j.rb. I wonder why the id was not included is json? If I keep using it, I would probably submit a pull request. Also, I wonder if it should be called just 'id' to keep with AR semantics? – Tim Scott Oct 17 '12 at 15:23
  • 1
    I don't know why it was not included. You're right with naming it `id`. I actually can't remember if I had a valid reason to call it `_nodeId`... – Vlad V Oct 24 '12 at 20:36
1

The ID is typically not included because it shouldn't be exposed outside the Neo4j database. Neo4j doesn't guarantee that the ID will be identical from instance to instance, and it wouldn't surprise me if the ID changed in a distributed, enterprise installation of Neo4j.

You should create your own ID (GUID?), save it as a property on the node, index it, and use that to reference your nodes. Don't expose the Neo4j ID to your users or application, and definitely don't rely on it beyond a single request (e.g. don't save a reference to it in another database or use it to test for equality).

Sean B
  • 33
  • 5