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! ๐
Share on
Twitter Facebook LinkedInHave comments or want to discuss this topic?
Send an email to ~bounga/public-inbox@lists.sr.ht