Rails version Within before_* Within after_* Cancel later callbacks Rails 1-4 return false return false Cancel later callbacks Rails 5+ throw :abort throw :abort Rollback the transaction

raise ActiveRecord::Rollback Rollback the transaction Rails 5+ throw :abort raise ActiveRecord::Rollback Take care that your callbacks don't accidentally return false, since that cancels the chain...

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

...of form.fields_for. You forgot to use accepts_nested_attributes in the containing model. Rails won't complain, but nothing will work. In particular, nested_form.object will be nil.

You are not setting the inverse_of for a has_many through association. Rails will then not be able to process a collection assignment, since it can't find...

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

...model validation that restricts its length. There are two motivations for this: In modern Rails, database types :string and :text no longer have a relevant size limit. Without a validation...

...malicious user can quickly exhaust the hard drive of your database server. In legacy Rails (or database schemas migrated from legacy Rails), database types :string and :text had a database...

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

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

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

makandracards.com

...config/initializers/searchkick.rb (or wherever you have configured your Searchkick settings) add: SEARCHKICK_CLIENT_TYPE = case Rails.env when 'production', 'staging', 'development', 'test' :elasticsearch else :opensearch end Searchkick.client_type = ENV.fetch('SEARCHKICK_CLIENT_TYPE...

...SEARCHKICK_CLIENT_TYPE).to_sym ENV['OPENSEARCH_URL'] ||= case Rails.env when 'production' OPENSEARCH_PRODUCTION_SERVER when 'staging' OPENSEARCH_STAGING_SERVER else 'http://opensearch:9200' # docker container name end

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

makandra dev
github.com

...All you need is a pretty print-stylesheet. How to use it from your Rails application You can have PDFKit render a website by simply calling PDFKit.new('http://google.com').to...

...separately before calling to_file. Alternatively you can use PDFKit::Middleware and all your Rails routes automagically respond to the .pdf format. This is awesome to get started fast, but...

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

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

makandra dev

...animation: none !important; } To only include these styles for tests, see Detect the current Rails environment from JavaScript or CSS. Disabling animations in Unpoly In Unpoly you can globally disable...

...argument('--disable-smooth-scrolling') Related cards Does or scroll the page? Detect the current Rails environment from JavaScript or CSS Disable concurrent AJAX requests in tests In applications that do...

Recent rails security updates have shown that people make incorrect assumptions about the possible contents of the params hash. Just don't make any! Treat it as what it is...

.../pages/edit?foo --> params == {:foo => nil} /pages/edit?foo[] --> params == {:foo => [nil]} # at least in older rails 3 and in rails 2.x Be especially wary about stuff like User.find_by_password...

...but give sub-classes a way to override values without affecting the parent class. Rails has many helpers for this such as class_attribute and class_inheritable_accessor. Unfortunately their...

...semantics are hard to understand, the helpers available differ for different versions of Rails and the behavior is subtly different. Make sure you read and understand the API before using...

To allow HTTP 304 responses, Rails offers the fresh_when method for controllers. The most common way is to pass an ActiveRecord instance or scope, and fresh_when will set...

The problem It might seem simple enough to just say: updated_at = Rails.cache.fetch('updated_at_of_expensive_scope') fresh_when last_modified: updated_at The example above calls...

...to be released when the block ends. Example: RSpec::Mocks.with_temporary_scope do allow(Rails).to receive(:env).and_return('production'.inquiry) puts Rails.env # prints "production" end puts Rails.env # prints...

...at the same time have a .where on an included table, two things happen: Rails tries to load all involved records in a huge single query spanning multiple database tables...

...activity.reload.users.ids # => [1, 2, 3, 4] Or you can reset the association cache: activity.users.reset # newer Rails activity.users(true) # old Rails In newer Rails versions you should prefer to use joins and...

...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 '&lt;span&gt;foo...

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

api.rubyonrails.org

...load associated records if you know you need to access them later on. The Rails docs say: Eager loading is supported with polymorphic associations. This is true, but has some...

...and include their current versions' primary media... Page.includes(:current_version => :primary_medium).to_a ... Rails will produce 4 queries: Page Load (0.7ms) SELECT "pages".* FROM "pages" PageVersion Load...

makandra dev
makandracards.com

Rails applications and ruby gems should have a README that gives the reader a quick overview of the project. Its size will vary as projects differ in complexity, but there...

...be written atop the class file. Structure I suggest the following outline for a Rails project's README, using the very readable Markdown language: # App title Describe the whole project...

Accept: application/json This means the client will only understand JSON responses. When a Rails action is done, it will try to render a template for a format that the...

...pages/foo, application/foo with {:locale=>[:de], :formats=>[:json], :handlers=>[:erb, :builder, :haml]} This is because Rails tried to find a template like foo.js.erb but all it found was foo.html.haml (which the...

...the threads terminate. This only affects threads that use ActiveRecord. You can rely on Rails' various clean-up mechanisms to release connections, as outlined below. This may cause your application...

...will allow in total. You can configure the maximum number of connections for each Rails process. This is called the size of your connection pool. The default pool size is...