ruby erb 36 lines · 4 tabs

Turbo Frames: infinite scroll with lazy-loading frame

Shared by codesnips Jan 2026
4 tabs
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)
  end
end
4 files · ruby, erb Explain with highlit

This snippet shows the standard Hotwire pattern for infinite scroll without writing any custom JavaScript, relying entirely on Turbo Frames and their built-in lazy-loading behavior. The core idea is that a Turbo Frame with loading="lazy" fetches its content only when it scrolls into the viewport, so each page of results ends with a frame that points at the next page. As the user scrolls, that frame becomes visible, requests the next page, and replaces itself with more posts plus a fresh next-page frame — forming a self-perpetuating chain until there is nothing left to load.

In PostsController, the index action paginates with Kaminari via page(params[:page]) and orders newest-first so pagination is stable. The controller does not branch on request format; the same ERB renders for both the full-page load and the lazy frame request, which keeps the logic minimal and lets Turbo do the swapping. @posts is exposed for the view, and .per(10) bounds each fetch so the frame stays cheap.

In index.html.erb, results live inside a turbo_frame_tag "posts_list" acting as the scroll container. Each post is rendered through the _post partial, and after the loop the _pagination partial emits the sentinel frame. The important detail is that the outer frame and the pagination frame have distinct IDs, so the incoming next page targets only the pagination region.

In _pagination.html.erb, next_page_url is computed from Kaminari's @posts.next_page; when it exists, a turbo_frame_tag with a unique id like page_2 and loading: "lazy" is rendered with its src pointing at the next page. When next_page is nil, nothing is rendered and the chain terminates naturally — an elegant base case that needs no flag.

The trade-off is that this pattern degrades to eager sequential requests rather than prefetching, and rapid scrolling can trigger several in-flight frame loads. It also depends on server-side pagination being deterministic; inserting rows between page fetches can shift results. For most feeds this is the simplest robust approach, and it works with the browser's back button and progressive enhancement out of the box.


Related snips

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: 'User'
  has_many :comments, dependent: :destroy

  scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
  scope :draft, -> { where(published_at: nil) }

ActiveRecord scopes for reusable query logic

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<form data-controller="query-sync" data-action="change->query-sync#apply">
  <select name="status" class="rounded border p-2">
    <option value="">Any</option>
    <option value="open">Open</option>
    <option value="closed">Closed</option>
  </select>

Filter UI that syncs query params via Stimulus (no front-end router)

rails hotwire stimulus
by Henry Kim 2 tabs
ruby
class SignupForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :account_name, :string
  attribute :email, :string

Shallow Controller, Deep Params: Form Object Pattern

rails activemodel form-object
by codesnips 3 tabs

Share this code

Here's the card — post it anywhere.

Turbo Frames: infinite scroll with lazy-loading frame — share card
Link copied