Method delegation in Rails can help you to keep your code organized and avoid deep call chains (law of demeter) by forwarding calls from one object to another. Rails provides...

...method_missing(method_name, *args, &block) @user.public_send(method_name, *args, &block) end end Rails shortcut: delegate_missing_to Because this is such a common pattern (e.g. for building something...

Rails gives you migrations to change your database schema with simple commands like add_column or update. Unfortunately these commands are simply not expressive enough to handle complex cases.

...card outlines three different techniques you can use to describe nontrivial migrations in Rails / ActiveRecord. Note that the techniques below should serve you well for tables with many thousand rows...

The default configuration of Rails disables CSRF protection in tests. If you accidentally forget to send the CSRF token for POST requests, your tests will be green even though your...

...under Selenium WebDriver is super-painful. It's much easier to detect the current Rails environment instead. You might be better of checking against the name of the current Rails...

...in a data-environment of your . E.g., in your application layout: <html data-environment=<%= Rails.env %>> Now you can say in a piece of Javascript: if (document.documentElement.dataset.environment == 'test') { // Code that should...

Several Rails migration methods accept index: true as an option to create an index. In some cases (like #add_column), this option is silently discarded. Know what you are doing...

...positive" btree (positive) "index_examples_on_user_id" btree (user_id) So what happened? Rails created indexes for all fields that we added inside our create_table statement.

As your Rails project grows, you will accumulate a number of small patches. These will usually fix a bug in a gem, or add a method to core classes.

...change_storage.rb fix_cache_ids.rb sanitize_filename_characters.rb ruby/ range/ covers_range.rb array/ dump_to_excel.rb xss_aware_join.rb enumerable/ collect_hash.rb natural_sort.rb string/ to_sort_atoms.rb rails/ find_by_anything.rb form_builder.rb form_for_with_development_errors.rb Note how all patches for standard library classes are in the ruby...

tekin.co.uk

Git diffs show the surrounding contexts for diff hunks. It does so by applying regular expressions to find the beginning...

Rails migrations allow you to use a change method whose calls are automatically inverted for the down path. However, if you need to some path-specific logic (like SQL UPDATE...

...at the same time. If you were to define define all 3 of them, Rails would only run change and ignore up and down. However, Rails 4+ features a helper...

...projects, which is being actively maintained and has test coverage for all versions of Rails...

...apply a significant score penalty. Here is how to do that automatically. Add premailer-rails to your Gemfile and bundle. Done! premailer-rails will automatically generate a text part for...

Actually, you may want to configure premailer-rails, and maybe tweak your HTML e-mail views a bit. Here are some suggestions. Open Rails' ActionMailer Previews and you will...

Rails credentials are a way to store secrets in an encrypted YAML file. Usage is simple: each key in the credentials file becomes a method on Rails.application.credentials, returning the corresponding...

# Credentials file file_storage_secret: superstrongsecret # Somewhere in the application FileStorage.secret = Rails.application.credentials.file_storage_secret Since credentials usually are different between environments, you can easily forget to define them for...

...the threads terminate. This only affects threads that use ActiveRecord. You can rely on Rails' various clean-up mechanisms to release connections, as outlined below. This may cause your application...

...will allow in total. You can configure the maximum number of connections for each Rails process. This is called the size of your connection pool. The default pool size is...

In Rails 8 the behavior of the rails db:migrate command has changed for fresh databases (see PR #52830). Before Rails 8: The command runs all migrations in the folder...

After Rails 8: The command loads the schema file (db/schema.rb or db/structure.sql) if existing and runs all pending migrations in the folder db/migrate/* afterwards This speeds up the command...

Note: Modern Rails has two build pipelines, the asset pipeline (or "Sprockets") and Webpacker. The principles below apply for both, but the examples shown are for Sprockets.

...request these assets again and again on every request. There is no magic in Rails that gives you automatic caching for assets. In fact, if you haven't been paying...

When dealing with time zones in Rails, there is one key fact to keep in mind: Rails has configurable time zones, while Ruby is always in the server's time...

...actually disable time zones, because their existence is a fact. You can, however, tell Rails the only single time zone you'll need is the server's. config.time_zone = "Berlin...

...readable form of the attribute: Person.human_attribute_name(:first_name) # => "First name" By default Rails will use String#humanize to format the attribute name, e.g. by replacing underscores with spaces...

...If no explicit translation is found, String#humanize is used. This card explains where Rails will look for custom attribute name translations in your locale files. Tip

From at least Rails 4, the ActionView tag helper turns Array values of HTML options into a single space-separated string. This means you can pass an array to :class...

It might sometimes be useful to check whether your Rails application accesses the file system unnecessarily, for example if your file system access is slow because it goes over the...

...which logs all system calls performed by a process. To do this, start your rails server using something like DISABLE_SPRING=1 strace -e trace=file -f bin/rails s

...check if your Postgres index can be used by a specific query in you Rails application. For more complex execution plans it might still be a good idea to use...

davidverhasselt.com

Rails 5 / 6 / 7 Method Uses Default Accessor Saves to Database Runs Validations Runs Callbacks Updates updated_at/updated_on Respects Readonly attribute= Yes No n/a n/a n/a n/a attributes= Yes

No No No No Note that update_attributes is no longer available on Rails 7 (it was only an alias to update before anyway). Rails 4 Method

...provide any built-in way of implementing authentication for the available DirectUpload endpoint in Rails. When using DirectUpload as JS wrapper in the frontend, be aware that its Rails endpoint...

...anyone to upload an unlimited amount of files to your storage. The DirectUploadController from @rails/activestorage bypasses your form controller because it uploads the file using an AJAX request that runs...

...to look up a fixture record. The same helper is not available in the Rails console, so debugging a fixture by name means looking it up by primary key (or...

...test environment the records are loaded automatically by the test runner. The initializer # config/initializers/fixture_console_helpers.rb Rails.application.configure do console do require 'active_record/fixtures' fixture_root = Rails.root.join('test/fixtures') helpers = Module.new do Dir.glob(fixture_root.join...

When upgrading Rails versions -- especially major versions -- you will run into a lot of unique issues, depending on the exact version, and depending on your app. However, it is still...

...to tackle the update in principle. If you are not really confident about upgrading Rails, have a look at Rails LTS. How many update steps? Besides the Rails upgrade itself...

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