...or a carnivore. Don't use self when defining scopes as class methods In Rails 2 and 5 (not 3, not sure about 4) there is one caveat you should...

...Do this instead: def self.suitable_for(user) if user.vegetarian? without_meat else all # for Rails 2 use `scoped({})` instead of `all` end end Note how we're returning #all instead...

Since Rails 7+ you can use ComparisonValidator for validations like greater_than, less_than, etc. on dates, numerics or strings. Example We have a model for booking a...

...before or equal to the start date') unless end_date.after?(start_date) end end Since Rails 7+ we can use the ComparisonValidator for these use cases. class TripBooking < ApplicationRecord validates :start...

...registered constants and the file references during the boot. Therefore you need to add Rails.autoloaders.log! at the end of your config/application.rb file. You could also run bin/rails zeitwerk:check for...

...script like this in lib/scripts/. But this folder is excluded by purpose from the Rails autoloading path and a Sidekiq worker will not find the required classes when invoked. So...

...take care of choosing the right class names to avoid wrong lookups caused by Rails autoloading mechanism. Part B Replace all paperclip code with carrierwave logic. Copy many parts from...

For Rails models where only one of multiple attributes may be filled out at the same time, there is no built-in validation. I've seen different solutions in the...

Sometimes, the rails dev server doesn't terminate properly. This can for example happen when the dev server runs in a RubyMine terminal. When this happens, the old dev server...

reinteractive.com

...to configure omniauth-multi-provider to support multiple SAML identity providers for a single Rails app: To solve this, the omniauth-multi-provider gem acts as a dynamic wrapper around...

Since Rails 6.1+ you can use .compact_blank or .compact_blank! to remove blank values from collections (e.g. arrays). Remove nil values from an array ['foo', nil].compact...

Remove blank values from collections Array array = [1, "", nil, 2, " ", [], {}, false, true] # Any Rails version array.reject(&:blank?) # => [1, 2, true] # Since Rails 6.1+ array.compact_blank # => [1, 2, true]

github.com

...eager-loading, and also if there is too much eager-loading. strict_loading in Rails 6.1+ forces developers to explicitly load associations on individual records, for a single association, for...

Testing your responses in Rails allows to parse the body depending on the response MIME type with parsed_body. get '/posts.json' response.parsed_body # => [{'id' => 42, 'title' => 'Title'}, ...]

...drop JSON.parse(response.body) and replace it with parsed_body. There also exists a cop Rails/ResponseParsedBody that you can enable via rubocop-rails...

...generates HTML. You can chain as many preprocessors as you want. When you deploy, Rails runs assets:precompile which precompiles all assets into static files that live in public/assets. This...

Modern IRB has time measurement built in. measure # Enable measure :off # Disable Custom Should your version of IRB not offer...

Within development and test environments, Rails is usually configured to show a detailed debug page instead of 404s. However, there might be some cases where you expect a 404 and...

...be used as a light-weight version of integration tests here.) In this case, Rails will replace the 404 page that you want to test for with its debug page...

Webpacker is Rails' way of integrating Webpack, and version 4 has been released just a few days ago, allowing us to use Webpack 4. I successfully upgraded an existing real...

...are notes on everything that I encountered. Note that we prefer not using the Rails asset pipeline at all and serving all assets through Webpack for the sake of consistency...

Look out for a number that keeps growing over time. Rails In a Rails application, you can use derailed_benchmarks to identify and examine memory leaks.

Note: Instead of using the method in this card, you probably want to use ActiveType's nested attributes which is...

apidock.com

...more than changing tables (like, modify many records) you may want some output. In Rails > 3.1 you have two methods at hand: announce and say_with_time. In the migration...

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

blog.saeloun.com

...want to find all Decks without any Card or all Cards without a Deck. Rails 6.1+ Rails 6.1 introduced a handy method ActiveRecord#missing to find records without given associations...

ON "decks"."id" = "cards"."deck_id" WHERE "decks"."id" IS NULL Older Rails versions If you don't have Rails 6.1 yet, you can use this not-so...

If validations failed for a record, and you want to find out if a specific validation failed, you can leverage...

...pass a :status option: get '/stories', to: redirect('/articles', status: 302) Note By default Rails sends a header Cache-Control: max-age=0, private, must-revalidate with all responses, including...

ActionMailer per default uses http as protocol, which enables SSL-stripping. When a logged-in user follows an http link...

Since Rails 6+ you can use before? and after? to check if a date/time is before or after another date/time. Example christmas = Date.parse('24.12.2022') date_of_buying_a...

tl;dr You should decouple migrations from models by embedding models into the migration. To use STI in this scenario...