...MySQL or PostgreSQL. Implementation examples are for the ActiveRecord ORM used with Ruby on Rails, but the techniques can be implemented in any language or framework. We will be using...
...the same object. You also know that you can reload an association to make Rails load its data from the database again. user.posts.reload # discards cache and reloads and returns user.posts...
...reset returns the association/scope. Hence, the above will not seem to work on the Rails console, just because the return value is inspected and thus resolved right away.
Zeitwerk is the new autoloader of Rails. It is mandatory starting with Rails 7.0. Sometimes, a model needs to know all its descendants. They might be organized in a subdirectory...
...needs to iterate all design subclasses. To eager load all designs, use this line: Rails.autoloaders.main.eager_load_dir(Rails.root.join 'app/models/design') Make sure that app/models/design.rb is not required manually before instructing Rails...
When your Rails controller action responds with only a simple text, render text: 'Hello' may not be what you want. You should not even use it on Rails 4.1+ any...
By default, a "text" response from a Rails controller will still be a sent as text/html: render text: 'Hello' response.body # => "Hello" response.content_type # => "text/html" While this may not be...
RSpec.configure do |config| config.include Aegis::Matchers end In very old versions of Rails and RSpec you need to do this instead: ActiveSupport::TestCase.send :include, Aegis::Matchers
...point over a separate ClassMethods module inside of your module. If you are using Rails (or only ActiveSupport), you may also use ActiveSupport::Concern which facilitates this for you.
...taken in chronological order, you get this: Singleton class Class Included modules Superclass(es) Rails 5 introduced prepended modules which allow you to patch methods in a class in a...
The Rails secret_token must be unique for each application and any instance of it. If not, someone could exploit this by creating a user with ID = 1 (e.g. on...
...current production users, leaving the production token unchanged: prefix the existing secret_token with #{Rails.env unless Rails.env.production?}. Note: There may be tokens in single quotes that include backslashes, double quotes...
...check Nokogiri::VersionInfo.instance.warnings for any warnings (though they should appear e.g. when launching a Rails console) or Nokogiri::VersionInfo.instance.to_hash to view more information. Note If your application uses Spring...
...collectiveidea.com/blog/archives/2012/01/27/testing-file-downloads-with-capybara-and-chromedriver module DownloadHelpers TIMEOUT = 10 module_function def download_path download_path = Rails.root.join("tmp/test_downloads#{ENV['TEST_ENV_NUMBER']}") FileUtils.mkdir_p(download_path) download_path end def clear_downloads FileUtils.rm...
Rails ships with two separate build pipelines: Sprockets ("asset pipeline") and Webpacker. Webpacker has many more moving parts, but allows us to use ES6 modules and npm packages (through Yarn...
Most web applications contain several examples of state machines, including accounts and subscriptions, invoices, orders, blog posts, and many more...
XPath matchers can be combined with CSS-selector matchers. This is really useful if not, for example, the content of...
...stack of tools. Start this card by skimming over the linked resource. Discussion Growing Rails applications in practice Read the following chapters from our book Growing Rails Applications in Practice...
...On following fashions Surviving the upgrade pace of Rails Owning your stack Discuss each chapter with your mentor. The Swinging Pendulum The XKCD about the sandboxing cycle is quite on...
SOURCE foo.dump \i foo.dump Further reading How to setup Ruby on Rails with PostgreSQL Connect to a Rails database with bin/rails dbconsole -p...
...without changing the return value: def save_user user.save.tap do |saved| next unless saved Rails.log("User was created, we have #{user.count} users now!") end end save_user # User was created...
.sort_by(&:last) .to_h end end Just paste that snippet into a Rails console and use #count_by now! Usage examples Number of email addresses by domain: > User.all.count...
...Article.all.count_by &:brand Note that the last simple example can also be achieved with Rails internals: Article.group(:brand).count. This translates to SQL, so it executes fast. However, grouping is...
Rails Active Support provides some helpful methods for calculating times and dates, like Duration#ago or Duration#from_now. But beware when using those, because they wont give...
...timezone unaware. Moreover, you have to be aware that ActiveSupport::TimeWithZone does not use Rails.application.config.active_record.default_timezone, which you need to define, even if you only use your local timezone, but...
# Redis db#1 is used for development. db_number = 1 if rails_env == 'test' normalized_test_number = [ENV['TEST_ENV_NUMBER'].to_i, 1].max db_number += normalized...
end db_number end def port case rails_env when 'staging' # when 'production' # else 6379 # default Redis port end end def rails_env defined?(Rails) ? Rails.env : ENV['RAILS...
...an unsubscribe token Each user needs a token that allows them to unsubscribe securely. Rails' signed_id works well for this: class FrontendUser < ApplicationRecord # ... def unsubscription_token return unless persisted...
Params are tricky Testing for request params is a little tricky because Rails hides details about how HTTP works. In particular GET requests encode their params in the URL...
...load the dump successfully, i.e. restore data for all the tables it contained (including Rails' schema_migrations). However, it would not remove any extra tables that were not part of...
When a user shares your content, a snippet with title, image, link and description appears in her timeline. By default...
...app/models/test.rb index eg3c1k1..843c0a2 31143 --- app/models/test.rb +++ app/models/test.rb @@ -19,6 +19,10 @@ module RoutingFilter path = Rails.root / 'app' + if true + + end + return path (1/1) Discard this hunk from worktree [y,n,q...
Pour color on your Rails console with awesome_print. Turn confusing long strings into formatted output. Have objects and classes laid out clearly whenever you need it. Put gem 'awesome...
...print', :group => :development into your Gemfile. Now on the Rails console you have the command ap that will give you a colored, formatted output of whatever you pass it. See...