Skip to content

Instantly share code, notes, and snippets.

@marinados
Last active May 4, 2016 07:29
Show Gist options
  • Save marinados/53d364c8b2c12829566d31900ae3ac88 to your computer and use it in GitHub Desktop.
Save marinados/53d364c8b2c12829566d31900ae3ac88 to your computer and use it in GitHub Desktop.

###Why?

Do you need to track objects by ID and look them up again, or look them up based on attributes, or even utilize some relational semantics, but have no real need for persistence?

PassiveRecord may be right for you!

###Features

  • Build relationships with belongs_to, has_one and has_many
  • Query on attributes and associations
  • Supports many-to-many and self-referential relationships
  • No database required!
  • Just include PassiveRecord to get started
require 'passive_record'

    class Model
      include PassiveRecord
    end

    class Dog < Model
      belongs_to :child
    end

    class Child < Model
      has_one :dog
      belongs_to :parent
    end

    class Parent < Model
      has_many :children
      has_many :dogs, :through => :children
    end

    # Let's build some models!
    parent = Parent.create
    => Parent (id: 1, child_ids: [], dog_ids: [])

    child = parent.create_child
    => Child (id: 1, dog_id: nil, parent_id: 1)

    dog = child.create_dog
    => Dog (id: 1, child_id: 1)

    # Inverse relationships
    dog.child
    => Child (id: 1, dog_id: 1, parent_id: 1)

    Dog.find_by child: child
    => Dog (id: 1, child_id: 1)

    # Has many through
    parent.dogs
    => [ ...has_many :through relation... ]

    parent.dogs.all
    => [Dog (id: 1, child_id: 1)]

    # Nested queries
    Dog.find_all_by(child: { parent: parent })
    => [Dog (id: 1, child_id: 1)]``
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment