...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...
...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...
...1M downloads), and geordi (> 200k downloads) Developing a Ruby gem is different from developing Rails applications, with the biggest difference: there is no Rails. This means: no defined structure (neither...
...to require all files yourself no active_support niceties Also, their scopes differ. A Rails application usually combines many libraries with custom code. It runs on a given version of...
...ActiveRecord scope. Depending on what you want to achieve, this is quite easy with Rails 7, and a bit more complicated with Rails 6 and below, or when the inverse...
...to get all users which are not part of User.admins, say: User.where.not(id: User.admins) Rails will generate a query like the following. SELECT * FROM users WHERE id NOT IN (SELECT...
Every modern Rails app should have a Content Security Policy enabled. Very compatible default The following "default" is a minimal policy that should "just work" for almost all applications
...you most of the benefits of a CSP In your config/initializers/content_security_policy.rb, set Rails.application.config.content_security_policy do |policy| policy.object_src :none policy.script_src :unsafe_eval, :strict_dynamic, :https # Browsers with support...
...subject line for each new mailer method. class SubjectPrefixInterceptor def self.delivering_email(message) message.subject = "[#{Rails.env}] #{message.subject}" end end unless Rails.env.production? ActionMailer::Base.register_interceptor(SubjectPrefixInterceptor) end Define it in an initializer...
@allowlists ||= {} @allowlists[environment] ||= Allowlist.new(config.fetch(environment, {})) end private def config @config ||= YAML.load_file(Rails.root.join('config/mail_allowlist.yml')).freeze end end extend ClassMethods end class AllowlistInterceptor def self.delivering_email(message) allowlist = AllowlistConfig.for...
...deploys or servers If you save your uploads to a made up directory like "RAILS_ROOT/uploads", this directory goes away after every deploy (since every release gets a new). Also...
Only two folders are, by default, shared between our application servers and deployments: "RAILS_ROOT/storage" and "RAILS_ROOT/public/system" (note that this might be different if you are not hosting...
...same pattern applies to any slow external API you want visibility on. Hooking into Rails' controller instrumentation allows us to get additional information like this in every log line:
...Ollama: 11443.1ms (queries: 8, input: 1218, output: 158) | GC: 87.7ms) This extends Rails 7 Server Timings, so the same numbers also show up in the browser's DevTools...
To add a few basic styles to the default error pages in Rails, just edit the default templates in public, e.g. public/404.html. A limitation to these default templates...
...is that they're just static files. You cannot use Haml, Rails helpers or your application layout here. If you need Rails to render your error pages, you need the...
Below is a strict, but still workable Content Security Policy for your Ruby on Rails project. Use this CSP if you want to be very explicit about what scripts you...
...config/initializers/content_security_policy.rb with the code below. Go through each comment and make adjustments where necessary. Rails.application.config.content_security_policy do |policy| # Allow nothing by default policy.default_src :none # Allow fetch and websocket...
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...
A Rails script lives in lib/scripts and is run with bin/rails runner lib/scripts/.... They are a simple tool to perform some one-time actions on your Rails application. A Rails...
...script has a few advantages over pasting some prepared code into a Rails console: Version control Part of the repository, so you can build on previous scripts for a similar...
Rails partials have a lot of "hidden" features and this card describes some non-obvious usages of Rails Partials. Rendering a basic partial The most basic way to render a...
...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...
Every Rails response has a default ETag header. In theory this would enable caching for multiple requests to the same resource. Unfortunately the default ETags produced by Rails are effectively...
...random, meaning they can never match a future request. Understanding ETags When your Rails app responds with ETag headers, future requests to the same URL can be answered with an...
...HTML-safe when translating with t('.your_key_html'). When you're localizing a Rails application, some localized texts need to contain HTML. Be it some localized link, or some...
...to learn more about <strong>the corporation</strong>. Alright. Rails is being helpful here and saves you from accidentally injecting HTML into the page. But how...
...the config.x configuration in combination with config_for to configure global settings for your Rails 4.2+ application. Example In your config/application.rb assign the settings from e.g. config/settings.yml as follows:
class Application < Rails::Application config.x.settings = config_for(:settings) end end The config/settings.yml might look as follows: shared: &shared email: info@example.com google_analytics: container: UA-123456-12 test: <<: *shared
Rails middlewares are small code pieces that wrap requests to the application. The first middleware gets passed the request, invokes the next, and so on. Finally, the application is invoked...
...can run rake middleware to get the ordered list of used middlewares in a Rails application: $> rake middleware use Webpacker::DevServerProxy use Rack::Sendfile use ActionDispatch::Static use Rack::LiveReload...
The new params.expect method in Rails 8 improves parameter filtering, addressing issues with malformed input and enhancing security. It provides a cleaner, more explicit way to enforce the structure and...
...hash or array) is provided for the permitted attributes. Example Basic Usage # Old before Rails 8 user_params = params.require(:user).permit(:name) # New since Rails 8 user_params = params.expect(user...
When an AJAX request raises an exception on the server, Rails will show a minimal error page with only basic information. Because all Unpoly updates work using AJAX requests, you...
...show with full CSS and JavaScript. The code assumes you are using Ruby on Rails with better_errors, which is the default error view that modern Rails versions employ. If...
...four variants, that add a more intuitive workflow when working with nested attributes in Rails + Unpoly: Without JS With HTML template and JS With HTML template and JS using dynamic...
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...
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...