3

I'm looking for a way to set up a relationship between Users where you can use in, out, and both all at the same time in Neo4j.rb.

Here's what I have so far:

class User
  include Neo4j::ActiveNode

  has_many :both, :friends, type: :connection, model_class: User
  has_many :out, :following, type: :connection, model_class: User
  has_many :in, :followers, type: :connection, model_class: User
end

The following works:

me = User.create
you = User.create

me.followers << you
me.followers.to_a
#=> [you]

you.following.to_a
#=> [me]

The opposite of above works as well. But this doesn't seem to work:

me.friends << you
you.following.to_a
#=> []

Or:

me.followers.to_a
#=> []

However, this does:

me.following.to_a
#=> [you]
bswinnerton
  • 4,533
  • 8
  • 41
  • 56

1 Answers1

4

This is expected behavior. Neo4j doesn't allow you to create relationships which don't have a direction. Thus, the both association type is only for querying (that is, when querying it specifies the relationship, but not the direction to/from the node).

Since Neo4j relationships always have a direction, when you create relationships with a both association it creates them as out relationships. See this section in the docs:

https://github.com/neo4jrb/neo4j/wiki/Neo4j-v3-Declared-Relationships#all-has_manyhas_one-method-calls-begin-with-declaration-of-direction

Thinking about it now, I'm wondering if perhaps Neo4j.rb shouldn't let you create relationships using both associations. What do you think? I'll create a Github issue as well

Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
  • Ah, that makes perfect sense. Digging into it a little bit deeper, it's a feature that I don't think that I would need either way. – bswinnerton Apr 08 '15 at 15:46
  • Great ;) The other thing I forgot to mention: You should get into the habit of using strings for `model_class` like this: , `model_class: 'User'` – Brian Underwood Apr 08 '15 at 16:17