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