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...
...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...
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...
...create only the records needed for the test. Learn Factories, not fixtures By default Rails uses global fixtures for its tests. This is a giant world of example data that...
...other gems in the past, but they all work in the same way. Watch Railscasts PRO #158 Factories not Fixtures (revised) for an introduction to factories in general and FactoryBot...
...README for the carrierwave gem Read about Common mistakes when storing file uploads with Rails Carrierwave: How to attach files in tests Carrierwave: Built-in RSpec matchers CarrierWave: Processing images...
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...
...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...
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...
...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...
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...
...generates HTML. You can chain as many preprocessors as you want. When you deploy, Rails runs assets:precompile which precompiles all assets into static files that live in public/assets. This...
...is rake good for? Take a look at some of the Rake tasks that Rails gives you (rake -T within a Rails project) Find the code that defines the rake...
...stats task in the Rails gems What are some ways how a Rake task can execute another task? What does it mean if a Rake task "depends" on another task...
This page lists many query methods and options in ActiveRecord which do not sanitize raw SQL arguments and are not...
...INFO -- : [53a240c1-489e-4936-bbeb-d6f77284cf38] more Goal When searching through Rails logs on production, it's often hard to see all lines that belong to the same requests, since...
...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...
Here is how to start your Rails application to accept both HTTP and HTTPS in development. gem install passenger Create a self-signed SSL certificate. Store the generated files in...
Watch Solving bizarre authorization requirements with Rails Read the Consul README Read the assignable_values README Understand how Consul and assignable_values can be used to implement arbitrary authorization...
...So might fix this by adding the following lines to your application.rb: class Application < Rails::Application config.time_zone = 'Berlin' # or whatever your time zone end It seems Date.yesterday uses the...
You don't want sensitive user data in your logs. Background Rails per default filters sensitive data like passwords and tokens and writes [FILTERED] to the logs. The...
...code which is responsible for enabling that usually lives in filter_parameter_logging.rb (Rails.application.config.filter_parameters). Here is an example of a filtered log entry: Unfiltered: `User Load (0.4ms) SELECT "users".* FROM...
Within development and test environments, Rails is usually configured to show a detailed debug page instead of 404s. However, there might be some cases where you expect a 404 and...
...be used as a light-weight version of integration tests here.) In this case, Rails will replace the 404 page that you want to test for with its debug page...
If validations failed for a record, and you want to find out if a specific validation failed, you can leverage...
Postgres supports multiple built-in range datatypes: int4range int8range numrange tsrange (range with timestamp without timezone) tstzrange (range with timestamp...