Rails 3, 4, 5, 6 config/application.rb config/environment.rb before the initialize! call (we don't usually edit this file) The current environment, e.g. environments/production.rb Gems Vendored plugins All initializers in config/initializers...

...initialize! call (we don't usually edit this file) Your own code from app Rails 2 Code in config/preinitializer.rb (if it exists) environment.rb, code above the Rails::Initializer.run block (put...

git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby "2.7.6" gem "rails", "~> 7.0.6" gem "sqlite3", "~> 1.4" gem "puma", "~> 5.0" This blocks automatic updates of rails, sqlite3 and puma...

git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby "2.7.6" gem "rails" gem "sqlite3" gem "puma" All gems are easily updateable with bundle update Good source "https://rubygems.org...

...an empty exclusion list returns no records at all! See below for better implementations. Rails 4+ Use the .not method to let Rails do the logic # Good User.where.not(id: []).to...

=> SELECT "users".* FROM "users" WHERE "users"."id" NOT IN (1, 2) Rails < 4 Before Rails 4, you needed to work around this yourself: # Good excluded_ids.blank? ? User.all : User.where("id...

Debugging performance issues in your Rails app can be a tough challenge. To get more detailed insights consider using the rack-mini-profiler gem. Setup with Unpoly Add the following...

...up.link.config.noFollowSelectors.push('.profiler-results a') document.addEventListener('up:link:follow', () => { if (window.MiniProfiler !== undefined) { window.MiniProfiler.pageTransition() } }) } # config/initializers/rack_mini_profiler.rb if Rails.env.development? Rails.application.config.to_prepare do Rack::MiniProfiler.config.position = 'top-right' # positon widget top-right Rack::MiniProfiler.config.skip_paths = [ # ignore...

simple_format ignores Rails' XSS protection. Even when called with an unsafe string, HTML characters will not be escaped or stripped! Instead simple_format calls sanitize on each of the...

...to escape yourself: simple_format(h(user_input)) Custom sanitization If you're using Rails 7.1 you can also customize your sanitize opions that simple_format uses. E.g if you...

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

...to add associations across those records, if they are related in some way. The Rails sandbox In development, Rails' sandbox mode might be useful. Testing and the migration codebase

...shoulda-matchers gem gives you some RSpec matchers to test the application of standard Rails validations. Under the hood should-matchers uses the same recipe as outlined above (set invalid...

...screen_name is not a palindrome. Since that check is not possible with standard Rails validations, we write a custom validation method like this: class User < ActiveRecord::Base validate :validate...

...add support for parallel tests. You can easily do that by setting config.root: config.root = "#{Rails.public_path}/system/#{Rails.env}#{ENV['TEST_ENV_NUMBER']}".freeze For debugging purposes (e.g. trying to hunt...

...separate environment. You you could read from an ENV variable instead of using your Rails.env. Suggested configuration In total, here is a suggested configuration that you can put into config/initializers/carrierwave.rb...

...security issues in web application, often known as "OWASP Top 10": https://owasp.org/www-project-top-ten/ Rails security Read the following sections from the Rails security guide. For each section you should...

...understand the security issue and what tools Rails gives you to address it. Cross-Site Request Forgery (CSRF) SQL Injection Cross-Site Scripting (XSS) Content Security Policy Also A reasonable...

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

api.rubyonrails.org

{ page_count: match[1].to_i } else {} end end rescue StandardError => e Rails.logger.error("PdfAnalyzer failed to parse metadata: #{e.message}") {} end def self.analyze_later? true # default end end # config/initializers/active_storage.rb...

...Rails.application.config.active_storage.analyzers.append PdfAnalyzer # db/migrate/xxxxx_add_pdf_analyzer.rb class AddPdfAnalyzer < ActiveRecord::Migration[8.0] def up pdf_blobs = ActiveStorage::Blob.where(content_type: 'application/pdf') # Mark all existing PDF blobs as to-be-analyzed-again pdf_blobs.find_each do...

...lot more gems than you think. E.g. when you do this: bundle update cucumber-rails ... you might think this will only update cucumber-rails. But it actually updates cucumber-rails...

...breaking API changes. Which is all the time. In the example above updating cucumber-rails will give you Capybara 2.0 (because capybara is a dependency of cucumber-rails), which will...

Resources Rails Guide: Internationalization API Guide to localizing a Rails application Locale-aware helpers in ActionView::Helpers::NumberHelper Accept-Language HTTP header. Can be parsed with a gem like...

Standard Rails translations The default strings used by Rails can be found in the rails-i18n repository. When we start a new project we often copy the German/English locale...

...Nested example groups before(:each) after(:each) let subject RSpec.configure, config.before, config.after Resources Everyday Rails Testing with RSpec (in our library), chapter 8 (Keeping Specs DRY) Note: Please refer to...

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

...can never change them without forcing users to empty their cache. Note By default Rails sends a header Cache-Control: max-age=0, private, must-revalidate with all responses, including...

...cached by browsers. You do need to pay attention if you redirect outside of Rails, e.g. via your web server configuration. Dealing with incorrectly cached redirects The only fix is...

Empty CSPs with send_file If you use send_file from a Rails controller, you can send potentially dangerous files with an inline disposition iff you also send...

...would execute active content): Content-Disposition: attachment If you use send_file from a Rails controller, the default disposition is attachment. You can also set it explicitly: send_file @attachment.path...

Understand how nested attributes appear in the params. See how the Rails form helpers encode the names of nested inputs. Understand how the record and all of its nested...

...saved in a transaction. That means the entire structure is saved or not. Resources Rails Guide: Nested forms Nested Forms in Rails Popular mistakes when using nested forms When aggregating...

...a named scope like Post.active and use that. Learn Resources Active Record Query Interface Rails Database Best Practices ActiveRecord: Specifying conditions on an associated table Preload, Eagerload, Includes and Joins...

...Battling n+1 Queries in Rails Tips Preventing scopes from loading A scope like User.where(email: 'foo@bar.com') does not make an SQL query. It simply returns a scope object for...

...runs; Code Reviews include test badge; Automatically merge a PR on green tests Upgrade Rails 5 0 - 5 New Rails features are accessible Replace slider framework 4 4

...comparison can often be seen with simple string comparison like so. # ❌ Not recommended if Rails.version > '6.1.7.8' || RUBY_VERSION > '3.1.4' raise Error, 'please check if the monkey patch below is still...

...comparison above works by coincidence. But chances are that you are not: For example, Rails version 6.1.10.8 would not raise an error in the code block above, because in an...

...sure not to mess with that. Related cards If you are using Ruby on Rails, a use case / implementation might look like Rails 3: Sending tempfiles for download.

makandra dev

...ALLOW_REMOTE_DATABASE_URL: 'true' DATABASE_URL: postgres://postgres:postgres@localhost:5432/test PGTZ: 'Europe/Berlin' RAILS_ENV: test TZ: 'Europe/Berlin' strategy: matrix: partition: [ 0, 1, 2, 3 ] # Keep in sync with...

...uses: actions/checkout@v4 - uses: ./.github/actions/setup-node - uses: ./.github/actions/setup-ruby - name: Setup database schema run: bundle exec rails db:create db:schema:load - name: Precompile assets run: bundle exec rails assets:precompile

makandra dev

...for consumption in browsers. Webpacker is a wrapper around webpack that handles integration with Rails. This is a short introduction. Installation If you haven't already, you need to install...

...x is still current! in your Gemfile. Run bundle install Finally, run bundle exec rails webpacker:install Alternatively, you can add webpacker from the start when creating a new Rails...