...you most likely want to use this in combination with the ActionDispatch::AssumeSSL middleware (Rails >= 7.1). This middleware makes your app assume that SSL terminates at the load balancer and...

...custom middleware to automatically flag all cookies as secure-only In a Ruby on Rails app you can add a middleware that automatically sets the Secure flag to all server...

...can specify your preferred version like so: bundle _2.1.2_ update --bundler Older Ruby and Rails cannot use the latest bundler 2 version, so you need to stay on bundler...

makandra dev

Getting CSS (and JS) live reloading to work in a esbuild / Rails project is a bit of a hassle, but the following seems to work decently well. We assume that...

...you already use a standard "esbuild in Rails" setup, and have an esbuild watcher running that picks up your source code in app/assets and compiles to public/assets; if not change...

...term, you can use PostgreSQL’s trigram similarity search. Writing a fuzzy query in Rails User.where("similarity(name, ?) > 0.3", "John") This finds all users where the name is similar to...

...setups. This can become pretty messy. The trick: spin up throwaway controllers with rspec-rails' anonymous controller helper, drive real requests, and classify the response. 2. Simplest possible case

...SomeController isn't sufficient here. It isolates routes. A bare routes.draw mutates the global Rails.application.routes. The helper swaps in a fresh RouteSet and restores it afterwards. It names the subclass...

api.rubyonrails.org

ActiveSupport (since 4.1) includes test helpers to manipulate time, just like the Timecop gem: To freeze the current time, use...

...have to either: Sort both the query and database content. If you're on Rails 7.1 you can use the new normalizes macro for this. This solution would still use...

Background information about session storage in Rails Rails has a default mechanism to store the session in the CookieStore. This is a cookie which holds the entire user session hash...

I recently stumbled upon the Rails feature composed_of. One of our applications dealt with a lot of addresses and they were implemented as 7 separate columns in the DB...

...enforced that. Because I used a regular class, I had to build it myself. The Rails-native readonly is sadly only available with ActiveRecord, not with ActiveModel. It would have...

api.rubyonrails.org

ActiveModel supplies an errors object that behaves similar to a Hash. It can be used to add errors to a...

greg.molnar.io

Greg Molnar has written a neat article about creating a single-file Rails app. This is not meant for production use but can be useful to try things out, e.g...

...when hunting down a bug or embedding a Rails app into the tests of a gem. What you do is basically: Put everything (gems, application config, database migrations, models, controllers...

apidock.com

All columns of a model's database table are automagically available through accessors on the Active Record object.

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

...using ActiveStorage's disk service. This means that stored files are served by your Rails application, and every request to a file results in (at least!) one non-trivial log...

...an example of what loading a single in an example application writes to the Rails log. Started GET "/rails/active_storage/blobs/redirect/..." for ::1 at ... Processing by ActiveStorage::Blobs::RedirectController#show as SVG...

By default, Rails' validates_uniqueness_of does not consider "username" and "USERNAME" to be a collision. If you use MySQL this will lead to issues, since string comparisons are case...

...may fail with an SQL error due to duplicate index key. You can change Rails' behaviour, by saying class User < ActiveRecord::Base validates_uniqueness_of :name, case_sensitive: false

if 'foo' =~ /foo/ puts $LAST_MATCH_INFO[1] # => foo end Require pitfall in Rails The English library is not loaded by default in Rails. So you or another library...

unpoly.com

Quick reference for passing data from Rails to JavaScript via Unpoly compilers. Haml Attribute Syntax # Ising hash rockets and string symbols (method calls) = form.text_field :name, 'date-picker': true

blog.saeloun.com

Rails' fragment caching caches subtrees of an HTML document tree. While constructing that tree though, it can be really hard to keep track of whether some code is run in...

...a caching context. Fortunately, Rails 7 brings two helpers that simplify this. Note that these helpers are all about Rails' fragment caching and not about downstream caching (i.e. Cache-Control...

...posts with a limited number of tags. The following chapters explain different approaches in Rails, how you can assign such an association via HTML forms. In most cases you want...

...with assignable values. The basic setup for all options looks like this: config/routes.rb Rails.application.routes.draw do root "posts#index" resources :posts, except: [:show, :destroy] end db/migrate/20230510093740_create_posts.rb class CreatePosts < ActiveRecord::Migration...

If you run a Rails app that is using Turbo, you might observe that your integration tests are unstable depending on the load of your machine. We have a card...

Rails' Strong Parameters enable you to allow only specific values from request params to e.g. avoid mass assignment. Usually, you say something like params.permit(:email, :password) and any extra parameters...

...scope :all_tags, -> (tags){ where('tags @> ARRAY[?]', tags) } end Document.create(title: "PostgreSQL", tags: ["pg","rails"]) Document.any_tags('pg') Document.all_tags(['pg', 'rails']) Migration: class CreateDocuments < ActiveRecord::Migration def change

...you have a maintenance script where you want to iterate over all ActiveRecord models. Rails provides this out of the box: # script/maintenance_task.rb # Load all models eagerly, otherwise you might only...

Rails.application.eager_load! ApplicationRecord.descendants.select(&:table_exists?).each do |model| # ... end Caution If you iterate over individual records, please provide a progress indicator: See https://makandracards.com/makandra/625369-upload-run-scripts-production Caution

Sometimes you need to remove high Unicode characters from a string, so all characters have a code point between 0...