By default, Rails views escape HTML in any strings you insert. If you want to insert HTML verbatim, you need to call #html_safe. However, #html_safe does not "unescape...
...is return a SafeBuffer which will handle future concatenations differently than a String. How Rails auto-escapes in views Rails renders your views into a SafeBuffer. It starts with an...
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...
...public site with many locales and an admin area with fewer locales). Gems: i18n-tasks, rails-i18n, optionally devise-i18n or other -i18n translations. File layout The Rails default puts...
6 backend exclusive files sometimes additional files if a language wasn't covered by rails-i18n or devise-i18n config/initializers/i18n.rb Derive the tiers from the locale files, so a...
...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...
...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...
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
...parallel by creating separate Git worktrees. Each worktree has its own working directory, but Rails will normally use the same development and test databases across all worktrees. This can cause...
...worktrees separate databases so parallel AI agents don't conflict. require 'digest' git = File.join((Rails.root rescue Dir.pwd).to_s, '.git') id = File.read(git)[%r{/worktrees/([^/\n]+)\s*\z}, 1] if...
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...
...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...
...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
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...
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...
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...
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...
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...
...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
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).
...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...
...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...
...table that is missing them. You can use the add_timestamps macros for that. Rails >= 4.2 Since Rails 4.2 add_timestamps also adds a NOT NULL constraint by default. So...
...SET updated_at = '#{time}'" # Restore NOT NULL constraints to be in line with the Rails default change_column_null :shows, :created_at, false change_column_null :shows, :updated_at, false...
...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