Whatโ€™s New in Ruby on Rails 8: Features, Code Examples, and Docs

Ruby on Rails 8 is here, bringing substantial performance improvements, modernized APIs, developer-friendly enhancements, and better security. This guide covers the latest features, code examples, and extracts from the official documentation, ensuring youโ€™re up to speed with the most powerful Rails version yet.


1. Performance Improvements with Turbocharged ActiveRecord

Rails 8 introduces optimizations to ActiveRecord, reducing query overhead and enhancing database interactions, leading to faster applications and better resource utilization.

๐Ÿ”ฅ Faster Query Execution with select_count

The new select_count method allows fetching record counts more efficiently, reducing database load and improving response times.

๐Ÿš€ Example

# Rails 7 - Standard count query
User.where(active: true).count

# Rails 8 - Optimized count query
User.where(active: true).select_count

๐Ÿ“Œ Extract from the docs:

โ€œThe select_count method optimizes count retrieval by reducing redundant SQL operations, leading to performance gains in large datasets.โ€

โœ… Why it Matters

  • Reduces unnecessary SQL load.
  • Improves query performance for large datasets.
  • Works seamlessly with existing ActiveRecord methods.

2. Hotwire Enhancements: Live Updates Made Easy

Rails 8 brings Hotwire 2.0, improving Turbo Streams and Stimulus for real-time updates without needing extensive JavaScript.

๐Ÿš€ Automatic Turbo Stream Broadcasting

Previously, developers had to manually broadcast changes using WebSockets. Now, Rails 8 handles broadcasting seamlessly with simple model configurations.

๐Ÿ“Œ Example

class Message < ApplicationRecord
  broadcasts_to ->(message) { [message.chat] }, inserts_by: :prepend
end

๐Ÿ“Œ Extract from the docs:

โ€œBroadcasting updates via Turbo Streams is now built into ActiveRecord, eliminating the need for external WebSockets configurations.โ€

โœ… Benefits

  • Real-time updates with minimal effort.
  • Improved performance and efficiency.
  • Less boilerplate code required.

3. Enhanced Background Jobs with ActiveJob 8

โณ Inline Processing for Low-Latency Jobs

ActiveJob now allows inline execution, bypassing queueing for lightweight jobs, allowing near-instantaneous processing in development environments.

๐Ÿš€ Example

class SendEmailJob < ApplicationJob
  queue_as :default
  executes_inline if: -> { Rails.env.development? }
end

๐Ÿ“Œ Extract from the docs:

โ€œInline job execution improves development testing by avoiding unnecessary queuing.โ€

โœ… Why This Matters

  • Reduces job queuing delays in local development.
  • Makes debugging easier and faster.
  • Improves flexibility when dealing with background jobs.

4. Built-in Support for Virtual Columns

Rails 8 introduces virtual columns, allowing computed columns to be stored and indexed at the database level for better performance.

๐Ÿš€ Example

class AddFullNameToUsers < ActiveRecord::Migration[8.0]
  def change
    add_column :users, :full_name, :string, as: "CONCAT(first_name, ' ', last_name)", stored: true
  end
end

๐Ÿ“Œ Extract from the docs:

โ€œVirtual columns enable faster computed fields without impacting Ruby-level performance.โ€

โœ… Benefits

  • Reduces calculation overhead in Rails models.
  • Improves query performance.
  • Enables indexing on computed fields.

5. Improved Security with Stronger Parameter Protection

๐Ÿ”’ Auto-Sanitization of Unsafe Parameters

Rails 8 enhances parameter handling, automatically rejecting unsafe inputs and enforcing stricter security policies.

๐Ÿš€ Example

params.permit(:name, :email, strict: true)

๐Ÿ“Œ Extract from the docs:

โ€œBy enforcing strict mode, developers can prevent mass-assignment vulnerabilities and avoid accidental data leakage.โ€

โœ… Why Itโ€™s Important

  • Prevents security vulnerabilities by default.
  • Reduces the risk of parameter tampering.
  • Improves application robustness.

6. New Debugging & Development Features

๐Ÿ›  Rails Console Gets Smarter

Rails 8 improves the Rails console with auto-completions, persistent history, and better debugging tools.

๐Ÿš€ Example

rails c --history

๐Ÿ“Œ Extract from the docs:

โ€œThe Rails console now supports persistent history and inline suggestions, making debugging easier.โ€

โœ… Why This Matters

  • Saves console command history between sessions.
  • Improves developer experience.
  • Reduces the need for external debugging tools.

7. Better API Support with JSON:API Improvements

๐ŸŒ Faster JSON Rendering with Jbuilder Enhancements

Rails 8 optimizes JSON serialization with Jbuilder 3.0, making API endpoints faster and more efficient.

๐Ÿš€ Example

json.extract! user, :id, :name, :email
json.posts user.posts, :title, :content

๐Ÿ“Œ Extract from the docs:

โ€œJbuilder 3.0 improves JSON rendering speeds by up to 30%.โ€

โœ… Why Itโ€™s Useful

  • Enhances API performance.
  • Reduces JSON generation time.
  • Improves response times for client applications.

8. Modern Asset Management with Propshaft

Rails 8 replaces Sprockets with Propshaft as the default asset pipeline. Hereโ€™s a comparison of the new workflow:

๐Ÿš€ Example

Old Sprockets configuration (Rails 7)

config/initializers/assets.rb:

Rails.application.config.assets.precompile += %w( custom.js )

New Propshaft configuration (Rails 8)

config/initializers/propshaft.rb:

Propshaft.configure do |config|
    config.paths << Rails.root.join(โ€œappโ€, โ€œassetsโ€, โ€œiconsโ€)
end

๐Ÿ“Œ Extract from the docs:

โ€œPropshaft provides a modern approach to asset management by leveraging import maps and HTTP2 server push capabilities. It eliminates the need for complex manifest files while maintaining compatibility with traditional asset pipeline concepts.โ€

โœ… Why Itโ€™s Useful

  • Simplified asset compilation
  • Better integration with modern JavaScript tools
  • Reduced configuration overhead

9. Production-Ready SQLite Integration

Rails 8 makes SQLite a first-class citizen for production use. Hereโ€™s how to configure it:

config/database.yml:

default: &default
    adapter: sqlite3
    pool: <%= ENV.fetch(โ€œRAILS_MAX_THREADSโ€) { 5 } %>
    timeout: 5000

development:
    <<: *default
    database: storage/development.sqlite3
    
production:
    <<: *default
    database: /var/www/myapp/storage/production.sqlite3

SQLite can be used to back complementary adapters:

  • Solid Queue: DB-based queuing backend for Active Job
  • Solid Cache: Database-backed Active Support cache store
  • Solid Cable: Database-backed Action Cable adapter that keeps messages in a table and continously polls for updates

10. Native Authentication Generator

Rails 8 introduces a built-in authentication system. Generate the base implementation with:

$ rails generate authentication

This creates:

  • app/models/user.rb
  • db/migrate/[timestamp]_create_users.rb
  • app/controllers/sessions_controller.rb
  • app/controllers/registrations_controller.rb

With this you can start with a simple authentication system and build upon it.


11. Progressive Web App (PWA) Support

Generate PWA baseline files with:

$ rails generate pwa:install

This creates:

  • app/views/application/manifest.json.erb
  • app/javascript/service-worker.js
  • app/notifiers/application_notifier.rb

Example notification system:

app/notifiers/post_notifier.rb:

class PostNotifier < ApplicationNotifier
  def new_comment(comment)
    notification(title: "New comment on #{comment.post.title}", body: comment.content.truncate(50), icon: comment.user.avatar_url)
  end
end

Trigger notification:

PostNotifier.with(comment: @comment).deliver_later(@post.author)

Conclusion

Rails 8 is a game-changer, bringing speed, security, and real-time capabilities to the forefront. Whether youโ€™re optimizing ActiveRecord, leveraging Hotwire for real-time updates, or securing parameters, Rails 8 delivers massive improvements.

๐Ÿš€ Key Takeaways:

  • ๐Ÿ”ฅ Faster ActiveRecord queries with select_count.
  • ๐Ÿ“ก Hotwire 2.0 simplifies real-time updates.
  • โณ Inline job execution improves development workflows.
  • ๐Ÿ›ก Stronger parameter protection for better security.
  • โšก Faster JSON API responses with Jbuilder 3.0.

Itโ€™s time to upgrade and unlock the full potential of Rails 8! ๐ŸŽ‰

Tags: ,

Updated:

Have comments or want to discuss this topic?

Send an email to ~bounga/public-inbox@lists.sr.ht