1

i try to create a custom getOrCreate method using find and if nothing is returned using create

my class :

class User
  include Neo4j::ActiveNode
  include Neo4jrbConcern

  property :name
  property :email

  validates :name, :presence => true
  validates :email, :presence => true
end

the method getOrCreate inherited from the concern

def getOrCreate(params)
  obj = self.find(params)
  if obj
    puts 'obj found : ' + obj
    return obj
  else
    return self.create(params)
  end
end

i'm trying this :

User.getOrCreate(
   name: data['name'],
   email: data['email']
)

the result is this error :

Neo4j::Session::CypherError: uuid not defined (line 1, column 86)
"MATCH (result_user:`User`) WHERE result_user.uuid.name = {result_user_uuid_name} AND uuid.email = {result_user_uuid_email} RETURN result_user ORDER BY ID(result_user) LIMIT {limit_1}"
                                                                                      ^
/Users/xxx/.rvm/gems/ruby-2.1.5/gems/neo4j-core-4.0.0/lib/neo4j-server/cypher_response.rb:166:in `raise_cypher_error'
/Users/xxx/.rvm/gems/ruby-2.1.5/gems/neo4j-core-4.0.0/lib/neo4j-core/query.rb:164:in `response'
/Users/xxx/.rvm/gems/ruby-2.1.5/gems/neo4j-core-4.0.0/lib/neo4j-core/query.rb:205:in `pluck'

do you see what i did wrong ?

thanks !

Benoît

armedwing
  • 113
  • 1
  • 10

1 Answers1

1

You can't pass a hash into find like that. It should be something like:

def getOrCreate(params)
  obj = self.where(params).first
  if obj
    puts 'obj found : ' + obj
    return obj
  else
    return self.create(params)
  end
end

Though this also seems like the perfect case for using a cypher MERGE which means you'd only need to do one query.

Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
  • @brian-unserwood thanks, i was lost in the doc. how would the code look like for a merge ? i'm trying this but i can't figure out how to return an object : ` query = Neo4j::Session.query .merge(q: {self.name => params}) obj = query.return(:q).to_a ` – armedwing Jan 27 '15 at 15:35
  • Yeah,that's close. `Neo4j::Session.query.merge(var: {ClassName: params}).pluck(:var).first` – Brian Underwood Jan 28 '15 at 11:22
  • Yours seems like it should work pretty well, what was the problem? – Brian Underwood Jan 28 '15 at 11:24
  • Yes, that was fine, thanks. i ended up with that : Neo4j::Session.query.merge(q: {self.name.to_sym => {uuid: uuid}}).on_create_set(q: params).pluck(:q).first – armedwing Feb 01 '15 at 13:11