Skip to content

Declared Relationships

Andreas Ronge edited this page Jul 21, 2014 · 8 revisions

has_many

A has_many declaration is used to generate accessor methods for traversing relationships as well as creating new relationships.

The first argument of the has_many is the name of the method that will be generated.

Example:

class Person
  include Neo4j::ActiveNode
  has_many :friends
end

This will generate a friends method on the Person class so that we can create new relationships between two nodes like this:

p = Person.create
p.friends << Person.create  # by default it creates an outgoing relationship of type friends

This could also be achieved without using the accessor method, example

p = Person.create
# example 1
p.outgoing(:friends) << Person.create  # Notice you don't have to declare the relationship !

# example 2
# See http://www.rubydoc.info/github/andreasronge/neo4j-core/Neo4j/Node#create_rel-instance_method
p.create_rel(:friends, Person.create, {}) # last argument is the properties of the relationship

Example: To retrieve all nodes using the friends accessor method

p.friends.to_a # [Person object, ...]

It is also possible to retrieve nodes without using the accessor method.

p.outgoing(:friends).to_a 

# or, see http://www.rubydoc.info/github/andreasronge/neo4j-core/Neo4j/Node#nodes-instance_method
p.nodes(...)

To retrieve the relationship object instead of the nodes, use the generated friends_rels method. Example

p.friends_rels.to_a  # [Neo4j::Relationship objects]

# this can also be done using the Neo4j::Node.rels method

has_many :to

The has_many method has an to parameter which can be used to generate accessor method for different outgoing relationships.

class Person
  include Neo4j::ActiveNode
  # map accessor method people_i_know to outgoing relationship :knows
  has_many :people_i_know, to: :knows  
end

has_many :from

The has_many method can also be used to generate accessor methods for incoming relationships.

class Person
  include Neo4j::ActiveNode
  has_many :known_by, from: :knows
end

Example, To create incoming relationships

p1 = Person.create
p2 = Person.create
p2.known_by << p1
p2.known_by.to_a # => [p1]

# this is the same as:
p1.people_i_know << p2
p2.known_by.to_a # => [p1]
Clone this wiki locally