Posted almost 3 years ago. Visible to the public.

Persisting trees

Storing a tree

For each movie in MovieDB, we want to track which other movie it was inspired by. For example:

  • "Interstellar was inspired by 2001"
  • "Inception was inspired by The Matrix"

Start by adding a field Movie#inspiration_id. In the movie form, I should be able to select the inspirating movie.

The list should:

  • include all the movies that were released in previous years
  • not include the movie itself
  • not include a movie that was itself inspired by the movie that is being edited.

Traversal

In the movie show view, I want to see the "inspiration tree" of that movie.

An inspiration tree for a movie M could look like this:

Copy
A | B | (M) / \ C D / \ F E

In the tree above I can see:

  • the current movie M was inspired by B
  • B was inspired by A
  • A has no recorded inspiration
  • C and D were inspired by M
  • F and E were inspired by D

Note that the user should see the same, complete tree no matter which movie in the structure she is currently viewing.

Look at your development log while opening a movie. How many queries are triggered?

Materialized path

  • Read about different patterns for storing trees in databases.
  • Migrate from Movie#inspiration_id to the materialized path pattern using the ancestry gem.
  • Make sure that you write a proper migration for existing movies.
  • Reduce the number of queries for the inspiration tree view to 2.
  • Look at the queries that ancestry is triggering. How does it work?

Owner of this card:

Avatar
Henning Koch
Last edit:
over 1 year ago
by Henning Koch
Posted by Henning Koch to makandra Curriculum
This website uses cookies to improve usability and analyze traffic.
Accept or learn more