ActiveRecord::Relation #with and #excluding

    The related pages feature on Joy of Rails queries on the pages and page_embeddings tables in the database. The query is backed two relatively new features in ActiveRecord: ActiveRecord::Relation#excluding and the yet-to-be-documented (as far as I know) ActiveRecord::Relation#with for representing Common Table Expressions (CTE).

    app/models/page.rb
    select("pages.*", "similar_embeddings.distance")
      .with(similar_embeddings: PageEmbedding.similar_to(page))
      .excluding(page)
      .order(distance: :asc)

    Back to snippets