...reason), you can open doc/dependency_decisions.yml and edit the last entry. A word on bower-rails Bower-rails is a Bower wrapper that simplifies Rails integration. Unfortunately, it makes it harder...

...to integrate Bower with LicenseFinder. To get things running, follow these steps: Symlink bower-rails's bower.json to the project root: ln -s vendor/assets/bower.json Create a .bowerrc file at the...

By default, Rails views escape HTML in any strings you insert. If you want to insert HTML verbatim, you need to call #html_safe. However, #html_safe does not "unescape...

...is return a SafeBuffer which will handle future concatenations differently than a String. How Rails auto-escapes in views Rails renders your views into a SafeBuffer. It starts with an...

...provide any built-in way of implementing authentication for the available DirectUpload endpoint in Rails. When using DirectUpload as JS wrapper in the frontend, be aware that its Rails endpoint...

...anyone to upload an unlimited amount of files to your storage. The DirectUploadController from @rails/activestorage bypasses your form controller because it uploads the file using an AJAX request that runs...

...Post < ApplicationRecord belongs_to :user validates :user, presence: true # Default for belongs_to on Rails 5+ end I18n has the feature of falling back one level to look up translations...

...at: Last change user: name: Name role: Access level # updated_at not needed here, Rails will use the definition from above Another feature of I18n is optional pluralization. When calling...

Rails' url_for is useful for generating routes from a Hash, but can lead to an open redirect vulnerability. Your application's generated route methods with a _url suffix are...

...Open Redirect vulnerability. It's as simple as passing a host=evil.tld URL parameter. Rails would see url_for(..., host: "evil.tld") and happily generate a URL to that foreign host...

api.rubyonrails.org

...ActiveRecord::Rollback, read on. The basic problem Not all databases support nested transactions. Therefore, Rails will sometimes silently ignore a nested transaction and simply reuse the other transaction. However, a...

...cause a roll back! To avoid this unexpected behaviour, you have to explicitly tell rails for each transaction to indeed use proper nesting: ActiveRecord::Base.transaction(joinable: false, requires_new: true...

...to set the default_url_options of ActionMailer: Hardcoded solution (preferred solution when using Rails with ActiveJob/Sidekiq or Cronjobs) Dynamic solution 1. Hardcoded solution When you are sending mails from...

...e.g. ActiveJob/Sidekiq or Cronjobs, you need to configure the default_url_options in your Rails configuration. # config/application.rb as fallback/default Rails.application.default_url_options = { host: 'localhost', port: 3000, protocol: 'http://' } Rails.application.configure do...

...column representing the filename of the file. To do this, add a new migration (rails g migration ) with the following content: class AddAttachmentToNotes < ActiveRecord::Migration[6.0] def change add_column...

...change the column details to fit your purpose. Run it. 1) Deliver attachments through Rails The first way is to store your Carrierwave attachments not in the default public/system, but...

makandracards.com

In medium-sized to large Rails applications, asset compilation can take several minutes. In order to speed up deployment, asset precompilation can be skipped. This card automates the process.

makandra dev

...treats cookies with SameSite=None like SameSite=Strict How to set a SameSite cookie Rails (session configuration) In config/initializers/session_store.rb, add the options secure: true, same_site: :strict|:lax. To set...

...none you need Rack 2 (i.e. Rails 5). Rails 6.1 will set SameSite=Lax; on default. Rails Custom cookies are set with cookies[:cookie_name] = 'value' or = { value: 'value', path...

...echo the environment setting in our application layout: <%= tag :meta, name: 'feature:polling', content: Rails.configuration.feature_polling %> Now polling is disabled by default for all tests. Our test suite has immediately...

...scenario 'The project list is updated periodically' do # Enable polling for this test allow(Rails.configuration).to receive(:feature_polling).and_return(true) # Go to the projects index and see an...

davidverhasselt.com

Rails 5 / 6 / 7 Method Uses Default Accessor Saves to Database Runs Validations Runs Callbacks Updates updated_at/updated_on Respects Readonly attribute= Yes No n/a n/a n/a n/a attributes= Yes

No No No No Note that update_attributes is no longer available on Rails 7 (it was only an alias to update before anyway). Rails 4 Method

...Further reading Order of the state_machine callback chain and how to abort it. Rails 5 does not halt callback chain if false is returned Legacy Rails versions...

Rails version Within before_* Within after_* Cancel later callbacks Rails 1-4 return false return false Rollback the transaction Rails 1-4 return false raise ActiveRecord::Rollback

With this command you can initiate an application restart without touching restart.txt. Unlike touching restart.txt, this tool initiates the restart...

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

Put the line below in the respective env.rb file to make your action controllers raise an ActionController::UnpermittedParameters error when...

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

...transactions and locking. Examples will be given for the ActiveRecord ORM (from Ruby on Rails), but apply to all technologies. Use transactions to group related changes Use a transaction to...

...than a single database row, you should always use a transaction. Note that in Rails, ActiveRecord::Base#save automatically opens a transaction. Hence changes you make in callbacks, nested attributes...

...the need for manual intervention that might destabilize or even crash the application. As Rails does not set a timeout on database statements by default, the following query will run...

...statement_timeout"=>"10s"}] begin ActiveRecord::Base.connection.execute("SELECT pg_sleep(15)") rescue ActiveRecord::QueryCanceled => e Rails.logger.error("Query was canceled: #{e.message}") end Adjust or disable the timeout for a single transaction:

makandra dev
api.rubyonrails.org

Rails includes a way to see what an e-mail will look like. Integration to RSpec All you need to do is implement a preview-class in spec/mailers/previews/notifier_preview.rb: class NotifierPreview...

end end And adapt the preview load path in your application.rb: config.action_mailer.preview_path = "#{Rails.root}/spec/mailers/previews" # For Rails < 7.1 config.action_mailer.preview_paths << "#{Rails.root}/spec/mailers/previews" # For Rails >= 7.1 Then a preview will...

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

github.com

...test using Capybara::Session#save_and_open_page and Capybara::Session#save_screenshot. Use Rails' built-in screenshot module If you want to avoid an external gem and use system...

...tests, you can also use Rails' built-in ScreenshotHelper module available for Rails >= 5. Including assets in HTML screenshots for prettier presentation Note Capybara takes two kinds of screenshots: a...

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

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