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

In Rails 5+ you can access a helper from a controller using the helpers method: # Inside a controller action helpers.link_to 'Foo', foo_path In older Rails versions you can...

The benefit of the Rails asset pipeline is that it compiles your stylesheets and javascripts to a single file, respectively. However, the consequences are startling if you don't understand...

...gave every library its own "root" folder. First, add this line to your config/initializers/assets.rb: Rails.application.config.assets.paths += Dir["#{Rails.root}/vendor/asset-libs/*"].sort_by { |dir| -dir.size } This will tell Rails about the custom asset...

To read the Rails session from a Rack middleware, use env['rack.session']. It's an ActionDispatch::Request::Session object. class MyMiddlware def initialize(app) @app = app end def call(env...

...status, headers, body = @app.call(env) session = env['rack.session'] Rails.logger.info("Value of session['foo'] is: " + session['foo'].inspect) [status, headers, body] end end You may not be able to write to...

...a situation in which I received the yarn integrity check warning when starting the rails console even though everything was up to date and correct versions in use.

I tried starting the rails console without switching to the correct node version first and received the yarn integrity warning. warning Integrity check: System parameters don't match...

edgeapi.rubyonrails.org

Starting from Rails 4.0, you can use a special form options helper called #collection_check_boxes. It behaves similar to #collection_select, but instead of a single select field it...

Note the hidden input at the end. This is a trick that Rails uses so users can uncheck all the check boxes. If this hidden input wasn't...

If your irb or rails console keeps randomly crashing and you can't figure out why then you can try to disable multi-line autocomplete...

} } } } } Integration in Rails + searchkick Was benötigt man für Integration von Elastic in eine Rails-Anwendung? Mindestens: Client um mit Elastic zu reden Erzeugen von Indexen, passender Mappings + Migration...