Skip to content

Neo4j.rb v3 Inheritance

Stayman Hou edited this page Jun 4, 2015 · 4 revisions

Index, properties and declared relationships (has_many and has_one) are inherited.

Example:

  class Vehicle
    include Neo4j::ActiveNode
    property :name, type: String
    index :name
  end

  class Car < Vehicle
    property :model
    index :model
  end

   bike = Vehicle.create(name: 'bike')
   volvo = Car.create(name: 'volvo', model: 'v60')
   saab = Car.create(name: 'saab', model: '900')

   Car.find_by(name: 'volvo') # => volvo
   Vehicle.find_by(name: 'volvo') # => volvo

   Car.find_by(model: '900') # => saab
   Vehicle.find_by(model: '900') # => saab

Working around circular dependencies

In some circumstances, an inherited class may crash with a circular dependency error.

class Contact
  include Neo4j::ActiveNode

  property :name
  property :email

  has_many :in, :bound_users, model_class: 'User'
end

class User < Contact
  include Neo4j::ActiveNode
end

2.1.1 :001 > User
RuntimeError: Circular dependency detected while autoloading constant User

# but load them in a different order...
2.1.1 :001 > Contact
 => Contact(email: Object, name: Object) 
# now it works
2.1.1 :002 > User
 => User(email: Object, name: Object) 

To work around this, use strings to represent related classes instead of class constants.

  class Vehicle
    include Neo4j::ActiveNode
    property :name
    index :name
  end

  class Car < Vehicle
    property :model
    index :model
  end
Clone this wiki locally