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...

There are multiple ways to redirect URLs to a different URL in Rails, and they differ in small but important nuances. Imagine you want to redirect the following URL...

api.rubyonrails.org

Rails offers a way to prepend (or append) view paths for the current request. This way, you can make the application use different view templates for just that request.

...action :prepare_views def index # ... end private def prepare_views if prepend_view_path Rails.root.join('app', 'views', 'special') end end end If is true, Rails will first look into app/views/special...

...That's not supported by our version managers like mise. Testing compatibility in a Rails project In general, a recent Rails projects should use the currently active LTS version of...

...from various browser extensions of your visitors. Add the endpoint in you CSP config/initializers/content_security_policy.rb: Rails.application.configure do config.content_security_policy do |policy| # Settings for the policy policy.report_uri '/content_security_policy_report' end

class ContentSecurityPolicyReportsController < ApplicationController skip_forgery_protection def create if request.content_type == 'application/csp-report' Rails.logger.info("Content Security Policy Report: #{request.user_agent} #{request.body.read}") head :ok else head :bad_request end

api.rubyonrails.org

In Rails 7.2. the feature ActiveRecord.after_all_transactions_commit was added, for code that may run either inside or outside a transaction (we have a special card for nested transactions...

...for custom handling, which now can be replaced by the build-in functionality of Rails. Note: This doesn't solve issues, where you want to have a specific order of...

Add gem 'database_cleaner' to your Gemfile. Then: Cucumber & Rails 3+ # features/support/database_cleaner.rb DatabaseCleaner.clean_with(:deletion) # clean once, now DatabaseCleaner.strategy = :transaction Cucumber::Rails::Database.javascript_strategy = :deletion Cucumber & Rails 2

...available cucumber-rails for Rails 2 automatically uses database_cleaner when cucumber/rails/active_record is required -- but only if transactional fixtures are off. To have database_cleaner work correctly: Add the attached...

api.rubyonrails.org

...is included in migrations by default (also see How to write complex migrations in Rails). Handy methods Note that both keys and values are always strings, i.e. you'll need...

...find out which parts of your application are not tested. Integrating this in a rails project with rspec, cucumber and parallel_tests is easy. Add it to your Gemfile and...

...gem 'simplecov', require: false end Add a .simplecov file in your project root: SimpleCov.start 'rails' do # any custom configs like groups and filters can be here at a central place...

In Rails 7.2 the new default for config.action_dispatch.show_exceptions is rescuable. :rescuable: It will show a Rails error page in the response only for rescuable exceptions as defined by ActionDispatch...

stack trace and a good debugging experience. :all: It will show a Rails error page in the response for all exceptions (previously true) :none: It will raise for...

Rails offers the fresh_when method to automatically compute an ETag from the given record, array of records or scope of records: class UsersController < ApplicationController def show @user = User.find(params...

Starting with Rails 7.1 the production logger is set to standard out. For applications running with opscomplete ensure to keep logging to a file as before (e.g. when running bin/rails...

...be enough to change these lines in the config/environments/production.rb back to the implementation in Rails <7.1: - # Log to STDOUT by default - config.logger = ActiveSupport::Logger.new(STDOUT) - .tap { |logger| logger.formatter = ::Logger::Formatter.new

...module structure. The typical example would be the concerns folder, which exists in new Rails applications by default and does not create a constant module Concerns. app ├── models    ├── concerns ├── shareable.rb...

...following official api: app ├── models    ├── shared ├── shareable.rb # Defines constant Shared::Shareable # e.g. in application.rb Rails.autoloaders.main.collapse("#{Rails.root}/app/models/shared") # with collapsed shared dir app ├── models    ├── shared ├── shareable.rb # Defines constant Shareable

...to set the default_url_options of ActionMailer: Hardcoded solution (preferred solution when using Rails with ActiveJob/Sidekiq or Cronjobs) Dynamic solution 1. Hardcoded solution When you are sending mails from...

...e.g. ActiveJob/Sidekiq or Cronjobs, you need to configure the default_url_options in your Rails configuration. # config/application.rb as fallback/default Rails.application.default_url_options = { host: 'localhost', port: 3000, protocol: 'http://' } Rails.application.configure do...

Rails has generic error messages you can define in your locale .yml files. You may override those application-wide error messages using model or attribute scope like this: en: activerecord...

This card will teach you how to index, search and rank your Rails models in a PostgreSQL full-text index. We will do this without using any gems...

...rolls back the transaction, nothing will be saved. The user will probably see a Rails error box. Improving the user experience In 99% of all cases adding a uniqueness key...

...is guaranteed. There are however cases where you want to improve the user behavior (Rails error box) or reduce the number of exceptions e-mailed to your / collected by your...

To reverse lookup a fixture by its table name and id, use the following approach on ActiveRecord::FixtureSet: table = 'users...

37signals.com

# Generate paths and URLs > app.project_path(Project.last) => "/projects/34" # Make requests > app.get '/projects/34' => 200 > app.response.body => " ..." # Use helpers helper.truncate("Foobar", length: 5...

Debugging performance issues in your Rails app can be a tough challenge. To get more detailed insights consider using the rack-mini-profiler gem. Setup with Unpoly Add the following...

...up.link.config.noFollowSelectors.push('.profiler-results a') document.addEventListener('up:link:follow', () => { if (window.MiniProfiler !== undefined) { window.MiniProfiler.pageTransition() } }) } # config/initializers/rack_mini_profiler.rb if Rails.env.development? Rails.application.config.to_prepare do Rack::MiniProfiler.config.position = 'top-right' # positon widget top-right Rack::MiniProfiler.config.skip_paths = [ # ignore...

...See this ES6 compatibility matrix for details. ES6 and Uglifier If you're using Rails with the assets pipeline (sprockets) you are probably using Uglifier to minify your JavaScript.

...can check if that's an issue for your project by running bundle exec rails assets:precompile in your development environment (don't forget to run bundle exec assets:clobber...

Rails offers several ways to remove records. They differ in whether they instantiate records, fire callbacks (including dependent: associations) and how they manage relation state afterward. destroy_all

...a few minor exceptions for our Austrian friends. Luckily, the I18n gem used by Rails has a fallback feature where you can make one locale file fall back to another...

... and another locale config/locales/de_AT.yml: de_AT: # only a handful exceptions here Now configure Rails to make de_AT fall back to de_DE: Rails.application.configure do config.i18n.fallbacks = { de_AT: :de...