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

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

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

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

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

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

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

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

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

Rails has always included a scaffold script that generates a default controller implementation for you. Unfortunately that generated controller is unnecessarily verbose. When we take over Rails projects from other...

...We prefer a different approach. We believe that among all the classes in a Rails project, controllers are some of the hardest to test and understand and should receive special...

The same applies to files in Carrierwave. Variant: Deliver attachments through Rails The first way is to store Paperclip attachments not in the default public/system, but in...

...can be configured like this: class Note < ActiveRecord::Base has_attached_file :attachment, :path => ":rails_root/storage/:rails_env/attachments/:id/:style/:basename.:extension" end To link to the protecting controller actions...

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

content_type_1.match(/\Aimage\/(jpeg|png)\z/) # => nil content_type_2.match(/\Aimage\/(jpeg|png)\z/) # => Rails Newer Rails explicitly warns you, when you use ^ and $ in validations with a regular expression...

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

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

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

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

github.com

gem 'super_diff' Require it in your spec_helper.rb require 'super_diff/rspec' # For Rails applications you can replace this with 'super_diff/rspec-rails' Customize colors in spec/support/super_diff.rb SuperDiff.configure do |config...

...contain exactly "XXX" ActiveRecord::Base is monkey patched by super_diff/rspec-rails (includes rspec and rails) super_diff/rails (includes active_record and active_support) super_diff/active_record This means that you have...

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

...up releases, not assets. In order to clean up assets, you can use capistrano-rails. Just require 'capistrano/rails' in Capfile and add the following config: # config/deploy.rb set :keep_assets...

...remove any older versions. If you are using Webpacker, you need to configure capistrano-rails. If you are on Rails 3, you cannot use this to clean up assets. :keep...

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

...characters that have a particular meaning in URLs, like & or =. If you are using Rails URL helpers like movies_path(:query => ARBITRARY_STRING_HERE), Rails will take care of the...