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]

...to some path methods generated by your routes. Even though you could technically include Rails.application.routes.url_helpers, this may include way too many methods and even overwrite some class methods in...

...advised to only make the desired methods available: class Project delegate :url_helpers, to: 'Rails.application.routes' def project_path url_helpers.project_path(self) end

position: relative left: -50% float: left .clear clear: both Together with this helper: # Rails 3 def center_float(&block) concat( content_tag(:div, :class => 'center_float_outer_container') do...

...tag(:div, :class => 'center_float', &block) end end + content_tag(:div, :class => 'clear') ) end # Rails 2 def center_float(&block) html = "".html_safe html << content_tag(:div, :class => 'center_float...

We recently migrated a Rails application from yarn to npm. We decided to go this step instead of upgrading to > Yarn 2.0 to reduce the number of dependencies in our...

...your yarn.lock (after the first npm install you can relax the constraints again). jsbundling-rails supports NPM since v1.2.2. geordi supports package managers other than yarn since v11.1.0...

...allows you to log to multiple sinks. You know this behavior from from the rails server command, that both logs to standard out and the log/development.log file.

...development.log file. Here is an example for Sidekiq: Sidekiq.configure_client do |config| if ENV['RAILS_ENV'] == 'development' || ENV['RAILS_ENV'] == 'test' stdout_logger = ActiveSupport::Logger.new(STDOUT) file_logger = ActiveSupport::Logger.new...

Code snippet tested with Rails 2.3 def index # ... if request.xhr? html = render_to_string(:partial => "list", :layout => false) respond_to do |format| format.html { render :text => html } format.json { render :json => {:html...

...this card might help. If you call render_to_string within the format.json block, Rails will only look for an index.json template, but not for an index.erb template...

This card describes how to install some tasks only for a given Rails environment or for a given Capistrano stage ("deployment target"). Installing jobs only for a given...

...Rails environment In your schedule.rb you may use environment variable to access the Rails environment of the current deployment: if environment == 'staging' every :day do # Setup job that will only...

By default most exceptions in Rails will render a 500 error page and will create a new issue in your error monitoring. There are some built-in rules in Rails...

To return non-HTML responses (like XLS spreadsheets), we usually use the respond_to do |format| format.xls do # send spreadsheet...

Sometimes, the rails dev server doesn't terminate properly. This can for example happen when the dev server runs in a RubyMine terminal. When this happens, the old dev server...

makandra dev
github.com

...note that some of the functions edge_rider provides have native implementations in newer rails versions. Useful in applications Relation#traverse_association(*names) Edge Rider gives your relations a method...

...These utilities are mostly useful in libraries that need to support multiple versions of Rails. They offer a unified interface across Rails versions. Relation#collect_ids You should not use...

...or a carnivore. Don't use self when defining scopes as class methods In Rails 2 and 5 (not 3, not sure about 4) there is one caveat you should...

...Do this instead: def self.suitable_for(user) if user.vegetarian? without_meat else all # for Rails 2 use `scoped({})` instead of `all` end end Note how we're returning #all instead...

For Rails models where only one of multiple attributes may be filled out at the same time, there is no built-in validation. I've seen different solutions in the...

Middleman is a static page generator that brings many of the goodies that Rails developers are used to. Out of the box, Middleman brings Haml, Sass, helpers etc. However, it...

...to do even better. This card is a list of improvement hints for a Rails developer. Gemfile Remove tzinfo-data and wdm unless you're on Windows. Add these gems...

...animated GIFs. Resizing them can be a time-consuming task and will block a Rails worker until the image is processed. Save yourself that trouble, and simply tell ImageMagick to...

...we still recommend the solution in this card. If you need to synchronize multiple rails processes, you need some shared resource that can be used as a mutex. One option...

Postgres supports multiple built-in range datatypes: int4range int8range numrange tsrange (range with timestamp without timezone) tstzrange (range with timestamp...

Since Rails 7+ you can use ComparisonValidator for validations like greater_than, less_than, etc. on dates, numerics or strings. Example We have a model for booking a...

...before or equal to the start date') unless end_date.after?(start_date) end end Since Rails 7+ we can use the ComparisonValidator for these use cases. class TripBooking < ApplicationRecord validates :start...

When deploying a Rails application that is using Webpacker and Capistrano, there are a few configuration tweaks that optimize the experience. Using capistrano-rails capistrano-rails is a Gem that...

...adds Rails specifics to Capistrano, i.e. support for Bundler, assets, and migrations. While it is designed for Asset Pipeline (Sprockets) assets, it can easily be configured for Webpacker. This brings...

In modern Rails versions you can also use ActiveRecord's pluck method. User.active.pluck(:id) => [1, 5, 23, 42] If you are plucking from the id column in particular you can...

...not the resulting array). Article.distinct.pluck(:state) # SELECT DISTINCT state FROM articles => ['draft', 'published'] In Rails 3 and 4 you must use uniq instead of distinct: Article.uniq.pluck(:state) # SELECT DISTINCT state...

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

rails-sqli.org

This page lists many query methods and options in ActiveRecord which do not sanitize raw SQL arguments and are not...

...script like this in lib/scripts/. But this folder is excluded by purpose from the Rails autoloading path and a Sidekiq worker will not find the required classes when invoked. So...

...take care of choosing the right class names to avoid wrong lookups caused by Rails autoloading mechanism. Part B Replace all paperclip code with carrierwave logic. Copy many parts from...

...for example, you maintain a gem and want to run automated tests against multiple rails versions. When you need to bundle one of your secondary Gemfiles, the solution above is...