1

Here is my Neo4j Model

class User
 include Neo4j::ActiveNode
 has_many :both, :followers, type: :following, model_class: 'User'
end

user1 has 2 out and 1 in like following

user1 ---> user2

user1 ---> user3

user1 <--- user3

If I query like following it returns both in/out

user1.followers.count #returns 3

I want to separately query in and out for a User

How can i do this with Neo4j.rb..

Thanks in advance.

Raj Adroit
  • 3,828
  • 5
  • 31
  • 44

1 Answers1

4

Since the association dictates how match Cypher is written, you can't override the method when called to change its behavior. The solution is to create two more associations.

class User
  include Neo4j::ActiveNode
  has_many :both, :followers, type: :following, model_class: 'User'
  has_many :out,  :following, type: :following, model_class: 'User'
  has_many :in,   :followed_by, type: :following, model_class: 'User'
  end
end

# Or, to make it feel more Ruby...

class User
  include Neo4j::ActiveNode
  [[:both, :followers], [:out, :following], [:in, :followed_by]].each do |dir, assoc|
    has_many dir, assoc, type: :following, model_class: 'User'
  end
end


2.2.0 :008 >   User.followers.to_cypher
 => "MATCH (node2:`User`), (result_followers:`User`), node2-[rel1:`following`]-(result_followers:`User`)" 
2.2.0 :009 > User.following.to_cypher
 => "MATCH (node2:`User`), (result_following:`User`), node2-[rel1:`following`]->(result_following:`User`)" 
2.2.0 :010 > User.followed_by.to_cypher
 => "MATCH (node2:`User`), (result_followed_by:`User`), node2<-[rel1:`following`]-(result_followed_by:`User`)" 
subvertallchris
  • 5,282
  • 2
  • 25
  • 43