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

api.rubyonrails.org

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

...you thought it would be, you don't understand how XSS protection works in Rails. Calling html_safe on the joined array will incorrectly bless the complete string as safe...

...string].join(' ').html_safe # will incorrectly render as ' foo bar ' with unescaped tags Good Rails >=3 safe_join([unsafe_string, safe_string], ' ') # will correctly render as '<span>foo...

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

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

Calling create or build on relations When you call create (or build) on a relation, the newly created record inherits...

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

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

Validations keep invalid data out of your database. This lesson covers Rails' built-in validations, how to test them, and how to show helpful error messages in your forms.

...Work on this lesson in teacher mode. Learning goals You can validate records with Rails' built-in validations and know where to look up the rest. You can explain why...

...you ask for it (and_call_original). You can explain which spec types rspec-rails offers besides model and feature specs, and write a request spec or a helper spec...

...render_template() matcher that helps with test above. To get this matcher, add a gem rails-controller-testing. Tip If you place your spec file in spec/requests you don't...

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

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

If you want someone to be able to access your rails console, but don't want them to be able to do changes you can use the rails console sandbox...

...invoking bin/rails console --sandbox. https://guides.rubyonrails.org/command_line.html#bin-rails-console To let one only access the sandbox rails console you can make use of the command option of OpenSSH: Specifies that the command...

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

apidock.com

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

Concurrent counter increments are a race-condition trap. The Rails idiom (load the record, increment in Ruby, save) breaks under concurrent writes. Between the read and the write, another transaction...

...This lesson covers the most common attacks like XSS, CSRF and SQL injection, how Rails protects you, and where you still need to be careful. Important Work on this lesson...

...building a file path from user input), session hijacking. You know which of these Rails prevents by default and where you still have to do the right thing yourself, e.g...

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

...groups are a useful RSpec feature. Unfortunately the default directory structure generated by rspec-rails has no obvious place to put them. I recommend storing them like this: spec/models/shared_examples/foo.rb spec/models/shared_examples/bar.rb...

...those shared examples available to all specs, put the following into your spec_helper.rb (for rails 4 in rails_helper.rb), above the RSpec.configure block: Dir[Rails.root.join("spec/models/shared_examples/**/*.rb")].each {|f| require f...

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

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