TL;DR When using Cache-Control on a Rails application, make sure the Vary: Accept header is set. Proxy caching is a good feature to serve your publicly visible application...

...but also affects proxies delivered by ISPs. Unfortunately, there is a little problem in Rails < 6.1 when delivering responses for different MIME-types. Say you have an arbitrary route in...

Dealing with exceptions in a Rails application is (surprisingly) complex. There are multiple configurations and methods that influence how exceptions are actually handled. This card explains some of the interactions...

...For debugging purposes it should be possible to see the stacktrace of the exception Rails' error handling default Rails' last resort for exceptions that noone else handled is called ExceptionApp...

makandra dev
impactahead.com

...object lists constants, ancestors with their methods, variables etc. Adding console helper methods # config/initializers/console.rb Rails.application.console do def custom_helper ... end end Generating paths app.root_path Making requests app.host = 'localhost'

...Rails has a method ActiveRecord::Relation#merge that can merge ActiveRecord scopes. However, its behavior has never been clear, and in Rails 7 it still discards conditions on the same...

When Rails releases a new version of their gems, they also release a number of npm packages like @rails/activestorage or @rails/actioncable. Unfortunately Rails uses up to 4 digits for their...

...digits and a pre-release suffix. To map gem versions and npm versions, Rails is going to use a naming scheme like this: Gem version

...shoulda-matchers gem gives you some RSpec matchers to test the application of standard Rails validations. Under the hood should-matchers uses the same recipe as outlined above (set invalid...

...screen_name is not a palindrome. Since that check is not possible with standard Rails validations, we write a custom validation method like this: class User < ActiveRecord::Base validate :validate...

...Post < ApplicationRecord belongs_to :user validates :user, presence: true # Default for belongs_to on Rails 5+ end I18n has the feature of falling back one level to look up translations...

...at: Last change user: name: Name role: Access level # updated_at not needed here, Rails will use the definition from above Another feature of I18n is optional pluralization. When calling...

...of form.fields_for. You forgot to use accepts_nested_attributes in the containing model. Rails won't complain, but nothing will work. In particular, nested_form.object will be nil.

You are not setting the inverse_of for a has_many through association. Rails will then not be able to process a collection assignment, since it can't find...

...card describes different flavors for concatting HTML safe strings in a helper method in Rails. You might want to use the tag helper instead of the content_tag helper (the...

...Further reading Order of the state_machine callback chain and how to abort it. Rails 5 does not halt callback chain if false is returned Legacy Rails versions...

Rails version Within before_* Within after_* Cancel later callbacks Rails 1-4 return false return false Rollback the transaction Rails 1-4 return false raise ActiveRecord::Rollback

Rails 8.1 ships the new ActiveSupport::ContinuousIntegration class. It allows you to list multiple steps. It will run all of them and fail if any of them exited non...

...The new Rails default seems to be a bin/ci file that's a small entry point and the real list of steps living in config/ci.rb. This seems like unnecessary indirection...

Programatically invoke Rails generators Require the generator, instantiate it and invoke it (because generators are Thor::Groups, you need to invoke them with invoke_all). Example: require 'generators/wheelie/haml/haml_generator'

...HamlGenerator.new('argument').invoke_all Other ways: Rails invokes its generators with Rails::Generators.invoke ARGV.shift, ARGV. From inside a Rails generator, you may call the inherited Thor method invoke(args=[], options...

This card shows how to upgrade a Rails 2 application from Rails 2.3.8 through every single patch level up to 2.3.18, and then, hopefully, Rails LTS. 2.3.8 to 2.3.9

...release has many minor changes and fixes to prepare your application for Rails 3. Step-by-step upgrade instructions: Upgrade rails gem Change your environment.rb so it says RAILS_GEM...

When your controller action raises an unhandled exception, Rails will look at the exception's class and choose an appropriate HTTP status code and error page for the response.

...instance, an ActiveRecord::RecordNotFound will cause Rails to render a red "The page you were looking for doesn't exist" with a status code of "404" (not found).

class World < ApplicationRecord; end class World::Earth < ApplicationRecord; end Without any further configuration, Rails will produce the following database table names. >> World.table_name => "worlds" >> World::Earth.table_name => "world_earths...

...to summarize by example the different uses of heredoc. In Ruby << vs. <<- vs. <<~ In Rails strip_heredoc vs. squish strip_heredoc should be used for a text, where you want...

Using heredoc for prettier Ruby code How to: Ruby heredoc without interpolation Rails 3+ def foo bar = <<-TEXT.strip_heredoc line1 line2 line3 TEXT puts bar.inspect end

Short reference on how to quickly debug the vanilla Rails job adapters. Queue Adapters by Environment Environment Adapter Jobs Run In Worker Needed? development :async Rails server process No

...Scripts and rake tasks log go to log/development.log Watch out for this within the Rails or development logs: Enqueued HelloJob (Job ID: xxx) to Async(asap) Performing HelloJob (Job ID...

simple_format ignores Rails' XSS protection. Even when called with an unsafe string, HTML characters will not be escaped or stripped! Instead simple_format calls sanitize on each of the...

...to escape yourself: simple_format(h(user_input)) Custom sanitization If you're using Rails 7.1 you can also customize your sanitize opions that simple_format uses. E.g if you...

...rare cases it's helpful to redirect the Logger output temporary to e.g. STDOUT. Rails.logger = Logger.new(STDOUT) ActiveRecord::Base.logger = Logger.new(STDOUT) User.save! #=> D, [2025-09-08T11...

...FROM "users" ORDER BY "users"."id" DESC LIMIT $1 [["LIMIT", 1]] Many frameworks in Rails have their own logger configuration and are set on boot. The example above configures the...

...I needed to do to add esbuild to an application that used the vanilla rails asset pipeline with sprockets before. Preparations update Sprockets to version 4 add a .nvmrc with...

...your preferred node version (and install it) add gems jsbundling-rails and foreman to your Gemfile: gem 'jsbundling-rails' group :development, :test do gem 'foreman' # ... end bundle install

postgresql.org

TL;DR PostgreSQL handles Rails 4+ text and string columns the same. Some libraries may still reflect on the column type and e.g. render differently sized text fields. PostgreSQL offers...

...costs. In most situations text or character varying should be used instead. Up to Rails 3, the column type string defaulted to creating a varchar column limited to 255 characters...

github.com

...test using Capybara::Session#save_and_open_page and Capybara::Session#save_screenshot. Use Rails' built-in screenshot module If you want to avoid an external gem and use system...

...tests, you can also use Rails' built-in ScreenshotHelper module available for Rails >= 5. Including assets in HTML screenshots for prettier presentation Note Capybara takes two kinds of screenshots: a...

...or an explanation for anything here, tailored to what you already know. Just ask. 📄 Rails Guide: Action Mailer Basics — mailers, views, delivery methods, previews and interceptors 📄 Action Mailer previews — our...

📘 Chapter "Task H1: Sending Confirmation Emails" from Agile Web Development with Rails 8 (in our library — check which edition we have) 📄 Valid recipients: Using the Truemail gem to validate...

...a has_many, has_one or belongs_to association, the :inverse_of option in Rails tells ActiveRecord that they're two sides of the same association. Example with a has...

...to :forum, inverse_of: :posts end Knowing the other side of the same association Rails can optimize object loading so forum and forum.posts[0].forum will reference the same object...