<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xml:lang="en-US">
  <title>BigBinary Blog: Rails 7</title>
  <subtitle>Deep technical writing on Ruby on Rails, performance, scaling, monitoring and engineering.</subtitle>
  <link rel="self" type="application/atom+xml" href="https://www.bigbinary.com/blog/categories/rails-7/feed.xml"/>
  <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/categories/rails-7"/>
  <id>https://www.bigbinary.com/blog/categories/rails-7</id>
  <updated>2024-01-16T00:00:00.000Z</updated>
  <author>
    <name>BigBinary</name>
    <uri>https://www.bigbinary.com/</uri>
  </author>
  <icon>https://www.bigbinary.com/favicon.ico</icon>
  <logo>https://www.bigbinary.com/images/bigbinary_square_big_logo.png</logo>
  <rights>Copyright 2024 Big Binary LLC</rights>
  <generator uri="https://nextjs.org">Next.js</generator>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 allows subscribing to transaction events]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-allows-subscribing-to-active-record-transaction-events"/>
      <link rel="enclosure" type="image/jpeg" href="https://www.bigbinary.com/blog/images/social_preview_images/rails_allows_subscribing_active_record_transaction_events.jpg"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-allows-subscribing-to-active-record-transaction-events</id>
      <published>2024-01-16T00:00:00.000Z</published>
      <updated>2024-01-16T00:00:00.000Z</updated>
      <author>
        <name>Vishnu M</name>
        <uri>https://www.bigbinary.com/blog/authors/vishnu-m</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/rails_allows_subscribing_active_record_transaction_events.jpg" width="1200" height="627"/>
      <summary type="text"><![CDATA[Rails 7.1 allows subscribing to Active Record transaction events for instrumentation.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-allows-subscribing-to-active-record-transaction-events"><![CDATA[<p>The Active Support instrumentation API provides us with hooks that allow us to
choose to be notified when certain events occur inside our application. Rails
provides a set of built-in events that we can subscribe to.
<a href="https://edgeguides.rubyonrails.org/active_support_instrumentation.html#rails-framework-hooks">Here</a>
is the list of framework hooks.</p>
<p>One of the recent additions to this is the <code>transaction.active_record</code> event
That is triggered when Active Record-managed transactions occur. This is
particularly useful if you want to build a monitoring system like NewRelic, where
you need to track and analyze database transactions for performance monitoring
and optimization purposes.</p>
<p>The event payload contains the connection, outcome, and the timing details. The
connection helps us identify the database where the transaction occurred, which
is particularly valuable in a multi-database environment. The outcome, which may
be one of the following: <code>:commit</code>, <code>:rollback</code>, <code>:restart</code>, or <code>:incomplete</code>
signifies the transaction's result.</p>
<p>To make use of this, we can subscribe to the event in an initializer
<code>config/initializers/events.rb</code> like this.</p>
<pre><code class="language-ruby">ActiveSupport::Notifications.subscribe(
  &quot;transaction.active_record&quot;
) do |event|
  MetricsLogger.record_transaction(event.payload)
end
</code></pre>
<p>In the above example, <code>MetricLogger</code> is responsible for recording the
transaction details. It then analyzes and reports slow transactions so that
proper action can be taken. You can modify this to suit your instrumentation
needs.</p>
<p>Please check out these pull requests -
<a href="https://github.com/rails/rails/pull/49192">1</a>,
<a href="https://github.com/rails/rails/pull/49262">2</a> for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 adds path_params option to url_for]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/url-for-path-params-options"/>
      <link rel="enclosure" type="image/jpeg" href="https://www.bigbinary.com/blog/images/social_preview_images/rails_adds_new_option_path_params_for_url_for_helper_method.jpg"/>
      <id>https://www.bigbinary.com/blog/url-for-path-params-options</id>
      <published>2023-11-07T00:00:00.000Z</published>
      <updated>2023-11-07T00:00:00.000Z</updated>
      <author>
        <name>Neenu Chacko</name>
        <uri>https://www.bigbinary.com/blog/authors/neenu-chacko</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/rails_adds_new_option_path_params_for_url_for_helper_method.jpg" width="1200" height="627"/>
      <summary type="text"><![CDATA[Rails 7.1 adds new option path_params for url_for helper method]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/url-for-path-params-options"><![CDATA[<p>With Rails 7.1, the <code>url_for</code> helper now supports a new option called
<code>path_params</code>.</p>
<p>Prior to Rails 7.1, if you had your routes configured to be scoped under say,
<code>user_id</code> as shown below, you would have to explicitly specify the <code>user_id</code> in
every single place where you want to generate a link for the scoped routes, such
as when writing view files.</p>
<pre><code class="language-ruby">#routes.rb
Rails.application.routes.draw do
  root &quot;articles#index&quot;

  scope &quot;:user_id&quot; do
    get &quot;/articles&quot;, to: &quot;articles#index&quot;
    get &quot;/articles/:id&quot;, to: &quot;articles#show&quot;
  end

  get &quot;/categories&quot;, to: &quot;categories#index&quot;
end
</code></pre>
<pre><code class="language-html">&lt;!-- app/views/articles/index.html.erb --&gt;

&lt;a href=&quot;&lt;%= articles_path(user_id: @current_user.id) %&gt;&quot;&gt; Articles &lt;/a&gt;
</code></pre>
<p>This could be solved by updating <code>ApplicationController</code> and overwriting the
<code>default_url_options</code> method:</p>
<pre><code class="language-ruby"># application_controller.rb
class ApplicationController &lt; ActionController::Base
  def default_url_options
    { user_id: &quot;unique-id&quot; }
  end
end
</code></pre>
<p>The <code>default_url_options</code> method is used to overwrite and set default options
for all the methods based on <code>url_for</code>. However, this meant that all routes,
even those that did not belong to the <code>user_id</code> scope, would have the
<code>?user_id=unique-id</code> query param added to the end of them, resulting in the
following output:</p>
<pre><code class="language-ruby">articles_path # =&gt; /unique-id/articles
categories_path # =&gt; /categories?user_id=unique-id
</code></pre>
<p>Rails 7.1 fixes this issue with the addition of the <code>path_params</code> option. If you
pass a hash of parameters to this key, those parameters will only be used for
the named segments of the route. If they aren't used, they are discarded instead
of being appended to the end of the route as query params.</p>
<p>With this change, we can implement the <code>default_url_options</code> method as follows:</p>
<pre><code class="language-ruby">class ApplicationController &lt; ActionController::Base
  def default_url_options
    { path_params: { user_id: &quot;unique-id&quot; } }
  end
end
</code></pre>
<p>The <code>url_for</code> helper method will now give you the following output:</p>
<pre><code class="language-ruby">articles_path # =&gt; /unique-id/articles
articles_path(user_id: &quot;test-id&quot;) # =&gt; /test-id/articles
categories_path # =&gt; /categories
categories_path(user_id: &quot;test-id&quot;) # =&gt; /categories
</code></pre>
<p>The view file can now be written as:</p>
<pre><code class="language-html">&lt;a href=&quot;&lt;%= articles_path %&gt;&quot;&gt; Articles &lt;/a&gt;
</code></pre>
<p>This is very useful in situations where you only want to add a required param
that is part of the route's URL without introducing unnecessary query params for
other routes.</p>
<p>Please check out this <a href="https://github.com/rails/rails/pull/43770">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 optimizes the default SQLite3 configuration]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-comes-with-an-optimized-default-sqlite3-adapter-connection-configuration"/>
      <link rel="enclosure" type="image/jpeg" href="https://www.bigbinary.com/blog/images/social_preview_images/rail_comes_with_an_optimized_sqlite3_adapter_connection_configuration.jpg"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-comes-with-an-optimized-default-sqlite3-adapter-connection-configuration</id>
      <published>2023-10-31T00:00:00.000Z</published>
      <updated>2023-10-31T00:00:00.000Z</updated>
      <author>
        <name>Vishnu M</name>
        <uri>https://www.bigbinary.com/blog/authors/vishnu-m</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/rail_comes_with_an_optimized_sqlite3_adapter_connection_configuration.jpg" width="1200" height="627"/>
      <summary type="text"><![CDATA[Rails 7.1 comes with an optimized default SQLite3 adapter connection configuration]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-comes-with-an-optimized-default-sqlite3-adapter-connection-configuration"><![CDATA[<p>The default SQLite3 Active Record adapter connection configuration has been
updated in Rails 7.1 to better tune it to work for modern Rails applications.</p>
<p>Before moving on to the configuration changes, let us understand what a PRAGMA is.
<a href="https://www.sqlite.org/pragma.html">PRAGMA</a> is a special kind of SQL
statement(only available in SQLite) which is used to query or manipulate various
aspects of the database's behaviour and configuration.</p>
<h2>Configuration Changes</h2>
<h3>1. <code>journal_mode</code> is now set use <code>WAL</code> instead of using the rollback journal</h3>
<p><a href="https://www.sqlite.org/pragma.html#pragma_journal_mode">journal_mode</a> is a
configuration setting in SQLite that determines how the database handles
transactions and maintains data integrity in the face of system crashes or
unexpected shutdowns. Previously, a brand new Rails application used to use the
rollback journal with <code>DELETE</code> journal mode. Now it uses a much more efficient
journaling method named Write-Ahead Logging (<code>WAL</code>). Let us understand the
difference between them.</p>
<p><strong>Rollback journal</strong>: In this implementation, the database engine first records
the original unchanged database content in a rollback journal, and the writes are
made directly to the database file. If the system crashes, the rollback journal
can be used to restore the database to the state it was in before the
transaction began. The issue with this approach is that a writer can alter the
database or readers can read from the database — but not both at the <strong>same</strong>
time.</p>
<p><strong>Write-ahead logging</strong>: In <code>WAL</code> mode, SQLite maintains a separate write-ahead
log. Instead of writing directly to the database file, changes are written to
the log first. When a reader needs a page of content, it first checks the <code>WAL</code>
to see if the page appears there, and if so it pulls in the latest copy of the
page in the <code>WAL</code>. If no copy of the page exists in the <code>WAL</code>, then the page is
read from the original database file. So this means readers and writers can work
together and there is no contention.</p>
<p><strong>How is the database file made up-to-date with the <code>WAL</code> file?</strong></p>
<p>SQLite routinely moves the <code>WAL</code> file transactions back into the database. This
process is called checkpointing. By default, SQLite does a checkpoint
automatically when the <code>WAL</code> file reaches a threshold size of 1000 pages.</p>
<p>If a system crash occurs, the last commit record has not been written to the
<code>WAL</code> file. Without the commit record, the new data is not considered valid, and
the database simply ignores it.</p>
<p><code>WAL</code> is a better choice for web applications because of the increased
concurrency it offers.</p>
<p><a href="https://fly.io/blog/sqlite-internals-wal/">Here</a> is a nice article on how <code>WAL</code>
works under the hood.</p>
<h3>2. <code>synchronous</code> is now set to <code>NORMAL</code> instead of <code>FULL</code></h3>
<p>The <a href="https://www.sqlite.org/pragma.html#pragma_synchronous">synchronous</a> pragma
controls how and when SQLite flushes content to disk. The two common options are
<code>FULL</code> and <code>NORMAL</code>, which map to “sync on every write” and “sync every 1000
written pages” respectively. <code>FULL</code> synchronous is very safe but slow. When
synchronous is <code>NORMAL</code>, the database engine will sync at the most critical
moments, but less often than in <code>FULL</code> mode. We trade an aggressive approach to
durability for speed.</p>
<p>The SQLite documentation suggests using <code>NORMAL</code> for applications running in
<code>WAL</code> mode.</p>
<h3>3. <code>journal_size_limit</code> is now capped at 64MB</h3>
<p>The
<a href="https://www.sqlite.org/pragma.html#pragma_journal_size_limit">journal_size_limit</a>
pragma tells SQLite how much of the write-ahead log data to keep in the on-disk
file. Previously, it was set to <code>-1</code> which means there was no limit set on the
journal size, which allows it to grow unbounded, thereby potentially affecting
read performance. Now it is capped at an appropriate size of 64MB.</p>
<h3>4. <code>cache_size</code> is now set to 8MB</h3>
<p>The <a href="https://www.sqlite.org/pragma.html#pragma_cache_size">cache_size</a> pragma
sets the maximum number of database disk pages that SQLite will hold in memory
at once, per open database file. The default value was -2000 i.e 2000 bytes.
Please note that SQLite interprets a negative value as a byte limit and positive
number as a page limit. Now the cache_size is set to 2000(pages) with a default
page size of 4096 bytes, which means the cache limit is ~8MB.</p>
<h3>5. <code>mmap_size</code> is now set to 128MB</h3>
<p>The <a href="https://www.sqlite.org/pragma.html#pragma_mmap_size">mmap_size</a> pragma sets
the maximum number of bytes that are set aside for memory-mapped I/O on a single
database. Let us first understand what memory-mapped I/O is.</p>
<p>Memory-mapped (mmap) I/O is an OS-provided feature that maps the contents of a
file on secondary storage into a program’s address space. The program then
accesses pages via pointers as if the file resided entirely in memory. The OS
transparently loads pages only when the program references them and
automatically evicts pages if memory fills up. The advantage of using mmap is that
it bypasses the step where we need to copy the pages from secondary to primary
storage, thereby making it faster.</p>
<p><strong>How is memory-mapped I/O implemented in SQLite?</strong></p>
<p>SQLite accesses and updates database files using <code>xRead()</code> and <code>xWrite()</code>
methods by default. These methods are typically implemented as <code>read()</code> and
<code>write()</code> system calls, which cause the OS to copy disk content between the
kernel buffer cache and user space. SQLite also has the option of accessing disk
content directly using memory-mapped I/O via the <code>xFetch()</code> and <code>xUnfetch()</code>
methods. Using the legacy <code>xRead()</code> method in SQLite, a page-sized heap memory
block is allocated, and the <code>xRead()</code> call copies the entire database page
content into this allocated memory. Whereas if memory-mapped I/O is enabled, it
calls the <code>xFetch()</code> method. The <code>xFetch()</code> method asks the operating system to
return a pointer to the requested page. If the requested page has been or can be
mapped into the application address space, then <code>xFetch()</code> returns a pointer to
that page for SQLite to use without having to copy anything. Skipping the copy
step is what makes memory-mapped I/O faster.</p>
<p>The <code>mmap_size</code> is the maximum number of bytes of the database file that SQLite
will try to map into the process address space at one time. Now it is set to
128MB.</p>
<p>With these changes, there is a considerable improvement in performance. That
being said, SQLite makes a strong case for single-node production applications,
as it is highly performant, especially when used in conjunction with NVMe disks.</p>
<p>Please check out this <a href="https://github.com/rails/rails/pull/49349">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 adds multi-column ordering to batch processing]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-adds-support-for-multi-column-ordering-in-activerecord-batches"/>
      <link rel="enclosure" type="image/jpeg" href="https://www.bigbinary.com/blog/images/social_preview_images/rails_adds_support_for_multi_column_ordering.jpg"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-adds-support-for-multi-column-ordering-in-activerecord-batches</id>
      <published>2023-10-03T00:00:00.000Z</published>
      <updated>2023-10-03T00:00:00.000Z</updated>
      <author>
        <name>Navaneeth D</name>
        <uri>https://www.bigbinary.com/blog/authors/navaneethsdk</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/rails_adds_support_for_multi_column_ordering.jpg" width="1200" height="627"/>
      <summary type="text"><![CDATA[Rails 7.1 adds support for multi-column ordering in ActiveRecord::Batches.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-adds-support-for-multi-column-ordering-in-activerecord-batches"><![CDATA[<p>In Rails 7.1, an enhancement has been introduced to
<a href="https://edgeapi.rubyonrails.org/classes/ActiveRecord/Batches.html"><code>ActiveRecord::Batches</code></a>
methods, related to models with composite primary keys. This update allows
developers to specify ascending or descending order for each key within a
composite primary key.</p>
<h3>Before Rails 7.1</h3>
<p>In Rails versions prior to 7.1, when batch processing records with a composite
primary key, like <code>id_1</code> and <code>id_2</code>, developers could use the <code>:asc</code> or <code>:desc</code>
argument to control the sorting order. However, there was a limitation in how
this sorting worked. When you specified the sorting order using <code>:asc</code> or
<code>:desc</code>, it affected both <code>id_1</code> and <code>id_2</code> simultaneously. In other words, if
you requested ascending order, both <code>id_1</code> and <code>id_2</code> would be sorted in
ascending order together. Similarly, if you requested descending order, both
<code>id_1</code> and <code>id_2</code> would be sorted in descending order together.</p>
<p>This limitation had practical implications, especially when you needed to sort
records by different criteria for each part of the composite primary key.</p>
<h3>After Rails 7.1</h3>
<p>With the new enhancement in Rails 7.1, developers can now select the sorting
order for each key within a composite primary key. Let's see this with an
example.</p>
<p>Consider a scenario where you have a <code>Product</code> model with a composite primary
key, <code>category_id</code> and <code>product_id</code>. You want to fetch products in descending
order of <code>category_id</code> and ascending order of <code>product_id</code>. With Rails 7.1, this
becomes straightforward:</p>
<pre><code class="language-ruby">class Product &lt; ActiveRecord::Base
  self.primary_key = [:category_id, :product_id]
end

# Retrieving products in descending order of
# category_id and ascending order of product_id
Product.find_each(order: [:desc, :asc]) do |product|
  # Your processing logic for each product goes here
end
</code></pre>
<p>The
<a href="https://edgeapi.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-find_each"><code>find_each</code></a>
method is a part of <code>ActiveRecord::Batches</code> and is used for efficient batch
processing of records from the database. It retrieves records in small batches,
reducing memory consumption and improving performance. The method takes an
optional <code>order</code> argument, which, as of Rails 7.1, can accept an array of
symbols to specify the sorting order for each key within the composite primary
key.</p>
<p>The enhancement for specifying sorting orders for composite primary keys is not
limited to <code>find_each</code>. It applies to other batch processing methods provided by
<code>ActiveRecord::Batches</code>, such
as<a href="https://edgeapi.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-find_in_batches"> <code>find_in_batches</code></a>
and
<a href="https://edgeapi.rubyonrails.org/classes/ActiveRecord/Batches.html#method-i-in_batches"><code>in_batches</code></a>.
These methods allow you to retrieve and process records in batches efficiently,
just like <code>find_each</code>.</p>
<h3>Conclusion</h3>
<p>In Rails 7.1, the support for multiple-column ordering in batches for models
with composite primary keys brings more flexibility and control to your
application's data retrieval process. Now you can tailor the sorting of
composite keys to match your specific needs, providing a more powerful and
versatile toolset for your Rails development endeavors.</p>
<p>Please check out this <a href="https://github.com/rails/rails/pull/48268">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 adds *_deliver callbacks to Action Mailer]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-adds-_-deliver-callbacks-to-action-mailer"/>
      <link rel="enclosure" type="image/jpeg" href="https://www.bigbinary.com/blog/images/social_preview_images/deliver_callbacks_for_action_mailer.jpg"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-adds-_-deliver-callbacks-to-action-mailer</id>
      <published>2023-09-26T00:00:00.000Z</published>
      <updated>2023-09-26T00:00:00.000Z</updated>
      <author>
        <name>Calvin Chiramal</name>
        <uri>https://www.bigbinary.com/blog/authors/calvinchiramal</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/deliver_callbacks_for_action_mailer.jpg" width="1200" height="627"/>
      <summary type="text"><![CDATA[Rails 7.1 has added \\deliver callbacks to Action Mailer. Let's understand the use of these callbacks with an example. Consider a case where you want to send an email after a user has signed up. When...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-adds-_-deliver-callbacks-to-action-mailer"><![CDATA[<p>Rails 7.1 has added *_deliver callbacks to Action Mailer. Let's understand the
use of these callbacks with an example. Consider a case where you want to send
an email after a user has signed up.</p>
<pre><code class="language-ruby">class UserMailer &lt; ApplicationMailer
  default from: 'notifications@neeto.com'

  def welcome_email
    @user = params[:user]
    mail(to: @user.email, subject: 'Welcome to neeto')
  end
end
</code></pre>
<p>When the <code>mail</code> method is called in the above code, it just renders the mail
template from a view. The mail is actually not sent. The actual delivery may
happen synchronously or asynchronously. To send the mail, we need to call one of
many deliver methods.</p>
<pre><code class="language-ruby">UserMailer.with(user: @user).welcome_email.deliver_later
</code></pre>
<p>Before Rails 7.1, we did not have any callbacks around the deliver methods to
execute code around the delivery lifecycle. You would need to use
<a href="https://guides.rubyonrails.org/action_mailer_basics.html#intercepting-and-observing-emails">interceptors and observers</a>
to hook into the mail delivery lifecycle. Say, you need to send emails to only a
few allowed email addresses in the staging environment. You would need to use an
interceptor and register it to Action Mailer.</p>
<pre><code class="language-ruby"># interceptors/staging_email_interceptor.rb
module Interceptors
  class StagingEmailInterceptor
    def self.delivering_email(mail)
      if rails.env.staging? &amp;&amp; !allowed_emails.include?(mail.to)
        mail.perform_deliveries = false
      end
    end
  end
end
</code></pre>
<pre><code class="language-ruby"># config/initializers/action_mailer.rb
ActionMailer::Base.register_interceptor(Interceptors::StagingEmailInterceptor)
</code></pre>
<p>The new <code>before_deliver</code> callback allows you to handle this situation without
using the Interceptors or Observers. You would just need to include the
following in <code>UserMailer</code>.</p>
<pre><code class="language-ruby">class UserMailer &lt; ApplicationMailer
  default from: 'notifications@neeto.com'
  before_deliver :filter_allowed_emails

  def welcome_email
    @user = params[:user]
    mail(to: @user.email, subject: 'Welcome to neeto')
  end

  private

    def filter_allowed_emails
      if rails.env.staging? &amp;&amp; !allowed_emails.include?(mail.to)
        mail.perform_deliveries = false
      end
    end
end
</code></pre>
<p>Similarly, suppose you want to update the <code>mail_delivered_at</code> attribute of the
<code>user</code> instance, you would have to use an observer and register it like so:</p>
<pre><code class="language-ruby"># observers/staging_email_interceptor.rb
module Observers
  class SetDeliveredAtObserver
    def self.delivered_email(mail)
      user = User.find_by(email: mail.to)
      user.update(mail_delivered_at: mail.date)
    end
  end
end
</code></pre>
<pre><code class="language-ruby"># config/initializers/action_mailer.rb
ActionMailer::Base.register_interceptor(Interceptors::StagingEmailInterceptor)
ActionMailer::Base.register_observer(Observers::SetDeliveredAtObserver)
</code></pre>
<p>With the new <code>after_deliver</code> callback this becomes as simple as defining a
method in <code>UserMailer</code>.</p>
<pre><code class="language-ruby">class UserMailer &lt; ApplicationMailer
  default from: 'notifications@neeto.com'
  before_deliver :filter_allowed_emails
  after_deliver :set_delivered_at

  def welcome_email
    @user = params[:user]
    mail(to: @user.email, subject: 'Welcome to neeto')
  end

  private

    def filter_allowed_emails
      if rails.env.staging? &amp;&amp; !allowed_emails.include?(mail.to)
        mail.perform_deliveries = false
      end
    end

    def set_delivered_at
      @user.update(mail_delivered_at: mail.date)
    end
end
</code></pre>
<p>An important thing to keep in mind is the order of execution of the callbacks.</p>
<ul>
<li>before_action</li>
<li>after_action</li>
<li>before_deliver</li>
<li>after_deliver</li>
</ul>
<p>This makes sense as the deliver callbacks only wrap around the deliver methods
while the action callbacks wrap around the mail render method.</p>
<p>Please check out this <a href="https://github.com/rails/rails/pull/47630">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 adds options to ActiveRecord::Relation#explain]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-adds-options-to-activerecord-relation-explain"/>
      <link rel="enclosure" type="image/jpeg" href="https://www.bigbinary.com/blog/images/social_preview_images/rails_detailed_query_plan_analysis.jpg"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-adds-options-to-activerecord-relation-explain</id>
      <published>2023-07-04T00:00:00.000Z</published>
      <updated>2023-07-04T00:00:00.000Z</updated>
      <author>
        <name>Vishnu M</name>
        <uri>https://www.bigbinary.com/blog/authors/vishnu-m</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/rails_detailed_query_plan_analysis.jpg" width="1200" height="627"/>
      <summary type="text"><![CDATA[Rails 7.1 enables detailed query plan analysis with options in ActiveRecord::Relation#explain.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-adds-options-to-activerecord-relation-explain"><![CDATA[<p>In Rails 7.1, an enhancement has been introduced to the
<a href="https://apidock.com/rails/ActiveRecord/Relation/explain"><code>ActiveRecord::Relation#explain</code></a>
method. This enhancement allows us to obtain detailed query plan analysis by
specifying options for the <code>explain</code> output.</p>
<h3>Understanding the EXPLAIN method</h3>
<p>Before diving into the new options available in Rails 7.1, let's quickly recap
the purpose and usage of the <code>explain</code> method in Active Record. The <code>explain</code>
method is used to retrieve the execution plan of an SQL query chosen by the
database optimizer. It provides insight into how the database intends to execute
the query, including the sequence of operations, indexes used, and estimated
costs.</p>
<p>By analyzing the query plan, we can identify potential performance bottlenecks,
optimize database schema design, and fine-tune queries for better efficiency.
However, prior to Rails 7.1, the level of detail available in the explain output
was limited.</p>
<h3>Detailed query plan analysis with options</h3>
<p>In Rails 7.1, the <code>explain</code> method accepts options, enabling us to customize the
output and obtain a more detailed query plan analysis. It's important to note
that these options are the same ones that are already available in native SQL.
Options may vary depending on the database used. In this blog post, we will
focus on examples using PostgreSQL. Let us take a look at some of the available
options.</p>
<h4>ANALYZE</h4>
<p>The <code>analyze</code> option causes the statement to be actually executed, not only
planned. Then actual run time statistics are added to the display, including the
total elapsed time expended within each plan node and the total number of rows
it actually returned.</p>
<pre><code class="language-ruby">Service.where('age &gt; ?', 25).joins(:user).explain(:analyze)
</code></pre>
<pre><code class="language-sql">EXPLAIN (ANALYZE) SELECT &quot;services&quot;.* FROM &quot;services&quot; INNER JOIN &quot;users&quot; ON &quot;users&quot;.&quot;id&quot; = &quot;services&quot;.&quot;user_id&quot; WHERE (age &gt; 25)
                          QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------
 Hash Join  (cost=15.50..29.42 rows=103 width=232) (actual time=0.015..0.017 rows=0 loops=1)
   Hash Cond: (services.user_id = users.id)
   -&gt;  Seq Scan on services  (cost=0.00..13.10 rows=310 width=232) (actual time=0.012..0.012 rows=0 loops=1)
   -&gt;  Hash  (cost=14.12..14.12 rows=110 width=8) (never executed)
         -&gt;  Seq Scan on users  (cost=0.00..14.12 rows=110 width=8) (never executed)
               Filter: (age &gt; 25)
 Planning Time: 0.915 ms
 Execution Time: 0.472 ms
</code></pre>
<h4>VERBOSE</h4>
<p>The <code>verbose</code> option provides a more detailed output by including additional
information about each step in the execution plan. This includes statistics,
cost estimates, and other relevant details.</p>
<pre><code class="language-ruby">Service.where('age &gt; ?', 25).joins(:user).explain(:verbose)
</code></pre>
<pre><code class="language-sql">EXPLAIN (VERBOSE) SELECT &quot;services&quot;.* FROM &quot;services&quot; INNER JOIN &quot;users&quot; ON &quot;users&quot;.&quot;id&quot; = &quot;services&quot;.&quot;user_id&quot; WHERE (age &gt; 25)
                          QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------
 Hash Join  (cost=15.50..29.42 rows=103 width=232)
   Output: services.id, services.user_id, services.provider, services.uid, services.access_token, services.access_token_secret, services.refresh_token, services.expires_at, services.auth, services.created_at, services.updated_at
   Inner Unique: true
   Hash Cond: (services.user_id = users.id)
   -&gt;  Seq Scan on public.services  (cost=0.00..13.10 rows=310 width=232)
         Output: services.id, services.user_id, services.provider, services.uid, services.access_token, services.access_token_secret, services.refresh_token, services.expires_at, services.auth, services.created_at, services.updated_at
   -&gt;  Hash  (cost=14.12..14.12 rows=110 width=8)
         Output: users.id
         -&gt;  Seq Scan on public.users  (cost=0.00..14.12 rows=110 width=8)
               Output: users.id
               Filter: (users.age &gt; 25)
(11 rows)
</code></pre>
<p>For more options available in PostgreSQL's EXPLAIN command, you can refer to the
<a href="https://www.postgresql.org/docs/current/sql-explain.html">official documentation</a>.</p>
<p>Please check out this <a href="https://github.com/rails/rails/pull/47043">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 adds ActiveRecord::Base::normalizes]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-adds-activerecord-base-normalizes"/>
      <link rel="enclosure" type="image/jpeg" href="https://www.bigbinary.com/blog/images/social_preview_images/rails_adds_activerecord_base_normalizes.jpg"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-adds-activerecord-base-normalizes</id>
      <published>2023-05-09T00:00:00.000Z</published>
      <updated>2023-05-09T00:00:00.000Z</updated>
      <author>
        <name>Abhijith Sheheer</name>
        <uri>https://www.bigbinary.com/blog/authors/abhijithsheheer</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/rails_adds_activerecord_base_normalizes.jpg" width="1200" height="627"/>
      <summary type="text"><![CDATA[Rails 7.1 adds ActiveRecord::Base::normalizes.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-adds-activerecord-base-normalizes"><![CDATA[<p>Rails 7.1 has introduced a new method in Active Record that can be used to
declare normalizations for attribute values. This can be especially useful for
sanitizing user input, ensuring consistent formatting, or cleaning up data from
external sources.</p>
<p>Before Rails 7.1, you could normalize attributes using <code>before_save</code> callback.</p>
<pre><code class="language-ruby">model User &lt; ApplicationRecord
  before_save :downcase_email, if :email_present?

  private

    def email_present?
      email.present?
    end

    def downcase_email
      email.downcase!
    end
end
</code></pre>
<p>In Rails 7.1, you can refactor the above to the code below.</p>
<pre><code class="language-ruby">model User &lt; ApplicationRecord
  normalizes :email, with: -&gt; email { email.downcase }
end
</code></pre>
<p>The normalization is applied when the attribute is assigned or updated, and the
normalized value will be persisted to the database. The normalization is also
applied to the corresponding keyword argument of finder methods. This allows a
record to be created and later queried using unnormalized values.</p>
<p>By default, normalization is not applied to <code>nil</code> values. To normalize
<code>nil</code> value, you can enable it using <code>:apply_to_nil</code> option.</p>
<pre><code class="language-ruby">model User &lt; ApplicationRecord
  normalizes :user_name, with:
    -&gt; user_name { user_name.parameterize.underscore }

  normalizes :email, with: -&gt; { _1.strip.downcase }

  normalizes :profile_image, with:
    -&gt; profile_image {
      profile_image.present? ? URI.parse(profile_image).to_s :
      &quot;https://source.boringavatars.com/beam&quot; },
    apply_to_nil: true
end
</code></pre>
<pre><code class="language-ruby"># rails console
&gt;&gt; User.create!(user_name: &quot;Eve Smith&quot;, email: &quot;eveSmith@EXAMPLE.com&quot;)

#&lt;User:0x000000010b757090 id: 1, user_name: &quot;eve_smith&quot;, profile_image:&quot;https://source.boringavatars.com/beam&quot;, email: &quot;evesmith@example.com&quot;, created_at: Wed, 03 May 2023 07:49:20.067765000 UTC +00:00, updated_at: Wed, 03 May 2023 07:49:20.067765000 UTC +00:00&gt;

&gt;&gt; user = User.find_by!(email: &quot;EVESMITH@example.COM&quot;)
&gt;&gt; user.email # =&gt; &quot;evesmith@example.com&quot;

&gt;&gt; User.exists?(email: &quot;EveSmith@Example.COM&quot;)          # =&gt; true
</code></pre>
<p>If a user's email was already stored in the database before the normalization
statement was added to the model, the email will not be retrieved in the
normalized format.</p>
<p>This is because in the database it's stored in mixed case, that is, without the
normalization. If you have legacy data, you can normalize it explicitly using
the <code>Normalization#normalize_attribute</code> method.</p>
<pre><code class="language-ruby"># rails console
&gt;&gt; legacy_user = User.find(1)
&gt;&gt; legacy_user.email  # =&gt; &quot;adamSmith@EXAMPLE.com&quot;
&gt;&gt; legacy_user.normalize_attribute(:email)
&gt;&gt; legacy_user.email  # =&gt; &quot;adamsmith@example.com&quot;
&gt;&gt; legacy_user.save
</code></pre>
<p>Please check out this <a href="https://github.com/rails/rails/pull/43945">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 logs the caller that enqueued a job]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-adds-support-for-logging-background-job-enqueue-callers"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-adds-support-for-logging-background-job-enqueue-callers.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-adds-support-for-logging-background-job-enqueue-callers</id>
      <published>2023-04-18T00:00:00.000Z</published>
      <updated>2023-04-18T00:00:00.000Z</updated>
      <author>
        <name>Vishnu M</name>
        <uri>https://www.bigbinary.com/blog/authors/vishnu-m</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-adds-support-for-logging-background-job-enqueue-callers.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.1 adds support for logging background job enqueue callers.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-adds-support-for-logging-background-job-enqueue-callers"><![CDATA[<p>Rails 7.1 has introduced a new option in Active Job that allows us to add
support for logging background job enqueue callers. It provides information
about the location from where a job was enqueued, which can be immensely helpful
during debugging. The following is an example of what the log output looks like:</p>
<pre><code class="language-ruby">[ActiveJob] Enqueued NotifySubscribersJob (Job ID: 5945980f-303e-4c3f-af5b-e22be170f7c5) to Sidekiq(default)
[ActiveJob] ↳ app/models/post.rb:14 in `notify_subscribers`
</code></pre>
<p>By examining the logs above, we can determine that the <code>NotifySubscribersJob</code>
was enqueued from the <code>notify_subscribers</code> method in the <code>Post</code> model, providing
us with a clear picture of the job's origin.</p>
<p>To enable this functionality, we need to set the following configuration in
<code>config/environments/development.rb</code>.</p>
<pre><code class="language-rb">config.active_job.verbose_enqueue_logs = true
</code></pre>
<p>However, Rails 7.1 ships with this configuration set by default.</p>
<p>It's important to note that using verbose enqueue logs in a production environment
is not recommended, as it uses the
<a href="https://apidock.com/ruby/Kernel/caller">Kernel#caller</a> method to retrieve the
execution stack, which can be slow.</p>
<p>Please check out this <a href="https://github.com/rails/rails/pull/47839">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 adds ActiveJob.perform_all_later]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-adds-activejob-perform-all-later"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-adds-activejob-perform-all-later.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-adds-activejob-perform-all-later</id>
      <published>2023-02-28T00:00:00.000Z</published>
      <updated>2023-02-28T00:00:00.000Z</updated>
      <author>
        <name>Vishnu M</name>
        <uri>https://www.bigbinary.com/blog/authors/vishnu-m</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-adds-activejob-perform-all-later.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.1 adds ActiveJob.perform_all_later to enqueue multiple jobs at once.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-adds-activejob-perform-all-later"><![CDATA[<p>Rails 7.1 adds <code>ActiveJob.perform_all_later</code> to enqueue multiple jobs at once.
This method accepts an array of job instances. Just like Active Record bulk
methods, <code>perform_all_later</code> doesn't run any callbacks.</p>
<p>For example, if we want to send a welcome email to multiple users, we can do
this:</p>
<pre><code class="language-ruby">welcome_email_jobs = users.map do |user|
  WelcomeEmailJob.new(user)
end

ActiveJob.perform_all_later(welcome_email_jobs)
</code></pre>
<p>The benefit of doing it this way, rather than looping through the user records
and using <code>perform_later</code> is that <code>perform_all_later</code> cuts down on the number of
round-trips to the queue datastore. That means reducing Redis round-trip latency
if the queuing backend is Sidekiq. Whereas if we're using a queuing backend like
<a href="https://github.com/bensheldon/good_job">GoodJob</a>, which is backed by Postgres,
<code>perform_all_later</code> will enqueue all the jobs using a single INSERT statement
which is more performant.</p>
<p>Please note that if the queuing backend doesn't support bulk enqueuing,
<code>perform_all_later</code> will fallback to enqueuing each job individually.</p>
<p>Active Job is designed to abstract away the differences between different job
processing libraries and to provide a unified interface. It is made possible
using
<a href="https://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html">adapters</a>.</p>
<p>The popular queuing backend Sidekiq already has a
<a href="https://github.com/sidekiq/sidekiq/wiki/Bulk-Queueing">push_bulk</a> method.
Hence, the author of this pull request has made
<a href="https://github.com/rails/rails/pull/46603/files#diff-e1ee600ca5fd100da20810ef5acbab89546064fc323c7b1e6bdb6ed5e681a9d3">changes</a>
to the Sidekiq adapter so that <code>perform_all_later</code> uses the <code>push_bulk</code> method
from Sidekiq.</p>
<p>Recently, GoodJob has also added support for bulk enqueuing in this
<a href="https://github.com/bensheldon/good_job/pull/790">pull request</a>.</p>
<p>Practically, <code>ActiveJob.perform_all_later</code> is only useful if we want to push
thousands of jobs at once. For a smaller number of jobs, the performance
benefits will not be significant.</p>
<p>Please check out this <a href="https://github.com/rails/rails/pull/46603">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 adds adapter option to disallow foreign keys]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-adds-adapter-option-to-disallow-foregin-keys"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-adds-adapter-option-to-disallow-foregin-keys.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-adds-adapter-option-to-disallow-foregin-keys</id>
      <published>2023-02-21T00:00:00.000Z</published>
      <updated>2023-02-21T00:00:00.000Z</updated>
      <author>
        <name>Aditya Bhutani</name>
        <uri>https://www.bigbinary.com/blog/authors/adityabhutani</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-adds-adapter-option-to-disallow-foregin-keys.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[There are times when an application can choose not to use foreign keys. Data transfer between services is a tricky thing. When we are importing the data, we need to import the data in the right order...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-adds-adapter-option-to-disallow-foregin-keys"><![CDATA[<p>There are times when an application can choose <strong>not</strong> to use foreign keys. Data
transfer between services is a tricky thing. When we are importing the data, we
need to import the data in the right order if &quot;foreign keys&quot; are enabled. In such
cases one might want to not enforce &quot;foreign keys&quot; and load the data and then
add &quot;foreign keys&quot; constraint back.</p>
<p>Situations like this can be handled using migrations. Using migrations, we can
disable &quot;foreign keys&quot;. However, this would mean writing migrations for all the
tables and removing all &quot;foreign keys&quot;. This could be cumbersome.</p>
<pre><code class="language-ruby">def change
  create_table :authors do |t|
    t.string :name
    t.timestamps
  end

  create_table :books do |t|
    t.belongs_to :author, foreign_key: false
    t.datetime :published_at
    t.timestamps
  end
end
</code></pre>
<p>Rails 7.1 adds an option to database.yml that enables skipping foreign key
constraints usage even if the underlying database supports them and solves the
above issue of writing migrations to disable foreign keys for all the tables.</p>
<pre><code class="language-yaml">development:
  &lt;&lt;: *default
  database: db/development.sqlite3
  foreign_keys: false
</code></pre>
<p>Please check out this <a href="https://github.com/rails/rails/pull/45301">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 allows aliased attributes in insert_all]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-allows-using-aliased-attributes-with-insert_all-upsert_all"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-allows-using-aliased-attributes-with-insert_all-upsert_all.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-allows-using-aliased-attributes-with-insert_all-upsert_all</id>
      <published>2023-01-11T00:00:00.000Z</published>
      <updated>2023-01-11T00:00:00.000Z</updated>
      <author>
        <name>Aditya Bhutani</name>
        <uri>https://www.bigbinary.com/blog/authors/adityabhutani</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-allows-using-aliased-attributes-with-insert_all-upsert_all.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.1 allows using aliased attributes with insert_all/upsert_all]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-allows-using-aliased-attributes-with-insert_all-upsert_all"><![CDATA[<p>Before Rails 6 we had update_all and delete_all. Rails 6 added insert_all and
upsert_all.</p>
<p><a href="https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert_all">insert_all</a>
: This method can insert multiple records with a single SQL INSERT statement.</p>
<p><a href="https://api.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-upsert_all">upsert_all</a>
: This method updates the records if they exist or inserts them into the
database with a single SQL INSERT statement.</p>
<p><a href="https://api.rubyonrails.org/classes/ActiveModel/AttributeMethods/ClassMethods.html#method-i-alias_attribute">alias_attribute</a>
: Allows you to make aliases for attributes, which include a getter, a setter,
and a predicate.</p>
<p>Rails 7.1 allows the use of aliased attributes with <code>insert_all</code> and <code>upsert_all</code>.
Previously whenever we added an alias for an attribute, we couldn't use it for
insert_all and upsert_all.</p>
<pre><code class="language-ruby">class User &lt; ApplicationRecord
  # database column is `name`. `full_name` is the alias.
  alias_attribute :full_name, :name
end
</code></pre>
<h3>Before Rails 7.1</h3>
<pre><code class="language-ruby"># rails console
&gt; User.insert_all [{ full_name: &quot;John Doe&quot; }]
=&gt; # unknown attribute 'full_name' for User. (ActiveModel::UnknownAttributeError)
</code></pre>
<h3>After Rails 7.1</h3>
<pre><code class="language-ruby"># rails console
&gt; User.insert_all [{ full_name: &quot;Jane Doe&quot; }]
=&gt; # User Insert

&gt; User.last
=&gt; #&lt;User id: 6, name: &quot;Jane Doe&quot;, created_at: Mon, 21 Nov 2022 18:07:11.349000000 UTC +00:00, updated_at: Mon, 21 Nov 2022 18:07:11.349000000 UTC +00:00&gt;
</code></pre>
<p>Now we can use the alias attribute with <code>insert_all</code> and <code>upsert_all</code>.</p>
<p>Please check out this <a href="https://github.com/rails/rails/pull/45036">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[How we upgraded from Rails 6 to Rails 7]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/how-we-upgraded-from-rails-6-to-rails-7"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-we-upgraded-from-rails-6-to-rails-7.png"/>
      <id>https://www.bigbinary.com/blog/how-we-upgraded-from-rails-6-to-rails-7</id>
      <published>2022-09-20T00:00:00.000Z</published>
      <updated>2022-09-20T00:00:00.000Z</updated>
      <author>
        <name>Abhishek T</name>
        <uri>https://www.bigbinary.com/blog/authors/abhishekt98</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-we-upgraded-from-rails-6-to-rails-7.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Recently, we upgraded all neeto products to Rails 7 using Rails upgrade guide. Here are the issues we faced during the upgrade. Migrating to Active Record Encryption This was the biggest challenge we...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/how-we-upgraded-from-rails-6-to-rails-7"><![CDATA[<p>Recently, we upgraded all <a href="https://www.neeto.com/">neeto</a> products to Rails 7
using
<a href="https://guides.rubyonrails.org/upgrading_ruby_on_rails.html">Rails upgrade guide</a>.</p>
<p>Here are the issues we faced during the upgrade.</p>
<h3>Migrating to Active Record Encryption</h3>
<p>This was the biggest challenge we faced during the upgrade. For encrypting
columns, we had used the
<a href="https://github.com/attr-encrypted/attr_encrypted">attr_encrypted</a> gem. However
Rails 7 came with
<a href="https://guides.rubyonrails.org/active_record_encryption.html">Active Record Encryption</a>.
So we needed to decrypt the records in the production database and encrypt them
using Active Record Encryption. We found that &quot;attr_encrypted&quot; gem was
incompatible with Rails 7. So the only option was to remove the &quot;attr_encrypted&quot;
gem and decrypt the records using a script. We used the following method to
decrypt the records.</p>
<pre><code class="language-rb">def decrypted_attribute(attribute_name, record)
  value = record.send(attribute_name)
  return if value.blank?

  value = Base64.decode64(value)

  cipher = OpenSSL::Cipher.new(&quot;aes-256-gcm&quot;)
  cipher.decrypt

  cipher.key = Rails.application.secrets.attr_encrypted[:encryption_key]
  cipher.iv = Base64.decode64(record.send(:&quot;#{attribute_name}_iv&quot;))

  cipher.auth_tag = value[-16..]
  cipher.auth_data = &quot;&quot;

  cipher.update(value[0..-17]) + cipher.final
end
</code></pre>
<h3>Broken images in Active Storage</h3>
<p>After the upgrade, we started getting broken images in some places. This
happened for Active Storage links embedded in Rich Text. After some debugging, we
found that we were getting incorrect Active Storage links because of a change in
the key generation algorithm. The following configuration was loading images
using the old algorithm.</p>
<pre><code class="language-rb">config.active_support.key_generator_hash_digest_class = OpenSSL::Digest::SHA1
</code></pre>
<p>Since the new algorithm provides more security, we decided to migrate the links
instead of using the old algorithm. We used the following code to migrate the
old link to the new valid link.</p>
<pre><code class="language-rb"># Usage:
# text_with_new_links = ActiveStorageKeyConverter.new(text_with_old_links).process
# If no links are there to replace, the original text will be returned as it is.

class ActiveStorageKeyConverter
  def initialize(text)
    @text = text
  end

  def process
    replace(@text)
  end

  private
    def convert_key(id)
      verifier_name = &quot;ActiveStorage&quot;
      key_generator =  ActiveSupport::KeyGenerator.new(Rails.application.secrets.
      secret_key_base, iterations: 1000, hash_digest_class: OpenSSL::Digest::SHA1)
      key_generator = ActiveSupport::CachingKeyGenerator.new(key_generator)
      secret = key_generator.generate_key(verifier_name.to_s)
      verifier = ActiveSupport::MessageVerifier.new(secret)

      ActiveStorage::Blob.find_by_id(verifier.verify(id, purpose: :blob_id))
      .try(:signed_id) rescue nil
    end

    def replace(text)
      keys = text.scan(URI.regexp).flatten.select{|x|
      x.to_s.include? (&quot;rails/active_storage&quot;)}.map{|x| x.split(&quot;/&quot;)[-2]}
      keys.each do |key|
        new_key = convert_key(key)
        text = text.gsub(key, new_key) if new_key
      end
      text
    end
end
</code></pre>
<p>Following one time rake task was used to update the Active Storage links in the
<code>content</code> column of <code>Task</code> model:</p>
<pre><code class="language-rb">desc &quot;Update active storage links embedded in rich text to support in rails 7&quot;
task migrate_old_activestorage_links: :environment do

  table_colum_map = {
    &quot;Task&quot; =&gt; &quot;content&quot;,
  }
  match_term = &quot;%rails/active_storage%&quot;

  table_colum_map.each do |model_name, column_name|
    model_name.to_s.constantize.where(&quot;#{column_name} ILIKE ?&quot;, match_term).find_each do|row|
      row.update_column(column_name, ActiveStorageKeyConverter.new(row[column_name]).process)
    end
  end
end
</code></pre>
<h3>Test failures with the mailer jobs</h3>
<p>After upgrading to Rails 7, tests related to mailers started to fail. This was
because the mailer jobs were enqueued in the <code>default</code> queue instead of
<code>mailers</code>. We fixed this by adding the following configuration.</p>
<pre><code class="language-rb">config.action_mailer.deliver_later_queue_name = :mailers
</code></pre>
<h3>Autoloading during initialization failed</h3>
<p>After the upgrade, if we startthe Rails sever then we were getting the following
error.</p>
<pre><code>$ rails s
=&gt; Booting Puma
=&gt; Rails 7.0.3.1 application starting in development
=&gt; Run `bin/rails server --help` for more startup options
Exiting
/Users/BB/Neeto/neeto_commons/lib/neeto_commons/initializers/session_store.rb:13:in
`session_store': uninitialized constant #&lt;Class:NeetoCommons::Initializers&gt;::ServerSideSession     (NameError)

    ActionDispatch::Session::ActiveRecordStore.session_class = ServerSideSession
                                                                ^^^^^^^^^^^^^^^^^
   from /Users/BB/Neeto/neeto-planner-web/config/initializers/common.rb:10:in `&lt;main&gt;'
</code></pre>
<p>That error was coming from our internal <code>neeto-commons</code> initializer called
<code>session_store.rb</code>. The code looked like this.</p>
<pre><code class="language-rb">#session_store.rb

module NeetoCommons
  module Initializers
    class &lt;&lt; self
      def session_store
        Rails.application.config.session_store :active_record_store,
          key: Rails.application.secrets.session_cookie_name, expire_after: 10.years.to_i

        ActiveRecord::SessionStore::Session.table_name = &quot;server_side_sessions&quot;
        ActiveRecord::SessionStore::Session.primary_key = &quot;session_id&quot;
        ActiveRecord::SessionStore::Session.serializer = :json
        ActionDispatch::Session::ActiveRecordStore.session_class = ServerSideSession
      end
    end
  end
end
</code></pre>
<p>In order to fix the issue we had to put the last statement in a block like shown
below.</p>
<pre><code class="language-rb">Rails.application.config.after_initialize do
 ActionDispatch::Session::ActiveRecordStore.session_class = ServerSideSession
end
</code></pre>
<h3>Missing template error with pdf render</h3>
<p>After the Rails 7 upgrade the following test started failing.</p>
<pre><code class="language-rb">def test_get_task_pdf_download_success
  get api_v1_project_section_tasks_download_path(@project.id, @section, @task, format: :pdf)

  assert_response :ok

  assert response.body.starts_with? &quot;%PDF-1.4&quot;
  assert response.body.ends_with? &quot;%EOF\n&quot;
end
</code></pre>
<p>The actual error is <code>Missing template api/v1/projects/tasks/show.html.erb</code>.</p>
<p>In order to fix it we renamed the file name from <code>/tasks/show.html.erb</code> to
<code>/tasks/show.pdf.erb</code>. Similarly we changed the layout from
<code>/layouts/pdf.html.erb</code> to <code>/layouts/pdf.pdf.erb</code>.</p>
<p>Initially the controller code looked like this.</p>
<pre><code class="language-rb">format.pdf do
  render \
    template: &quot;api/v1/projects/tasks/show.html.erb&quot;
    pdf: pdf_file_name,
    layout: &quot;pdf.html.erb&quot;
end
</code></pre>
<p>After the change the code looked like this.</p>
<pre><code class="language-rb">format.pdf do
  render \
    template: &quot;api/v1/projects/tasks/show&quot;,
    pdf: pdf_file_name,
    layout: &quot;pdf&quot;
end
</code></pre>
<h3>Open Redirect protection</h3>
<p>After the Rails 7 upgrade the following test started failing.</p>
<pre><code class="language-rb">def test_that_users_are_redirected_to_error_url_when_invalid_subdomain_is_entered
  invalid_subdomain = &quot;invalid-subdomain&quot;

  auth_subdomain_url = URI(app_secrets.auth_app[:url].gsub(
   app_secrets.app_subdomain, invalid_subdomain))

  auth_app_url = app_secrets.auth_app[:url]

  host! test_domain(invalid_subdomain)
  get &quot;/&quot;

  assert_redirected_to auth_app_url
end
</code></pre>
<p>In the test we are expecting the application to redirect to <code>auth_app_url</code> but
we are getting <code>UnsafeRedirectError</code> error for open redirections. In Rails 7 the
new Rails defaults
<a href="https://api.rubyonrails.org/v7.0.3.1/classes/ActionController/Redirecting.html#method-i-redirect_to-label-Open+Redirect+protection">protects</a>
applications against the
<a href="https://cwe.mitre.org/data/definitions/601.html">Open Redirect Vulnerability</a>.</p>
<p>To allow any external redirects we can pass <code>allow_other_host: true</code>.</p>
<pre><code class="language-rb">redirect_to &lt;External URL&gt;, allow_other_host: true
</code></pre>
<p>Since we use open redirection in many places we disabled this protection
globally.</p>
<pre><code class="language-rb">config.action_controller.raise_on_open_redirects = false
</code></pre>
<h3>Argument Error for Mailgun signing key</h3>
<p>After the upgrade, we started getting the following error in production.</p>
<pre><code>&gt;&gt; ArgumentError: Missing required Mailgun Signing key. Set action_mailbox.mailgun_signing_key
in your application's encrypted credentials or provide the MAILGUN_INGRESS_SIGNING_KEY
environment variable.

</code></pre>
<p>Before Rails 7, we used the <code>MAILGUN_INGRESS_API_KEY</code> environment variable to
set up the
<a href="https://guides.rubyonrails.org/action_mailbox_basics.html#mailgun">Mailgun signing key</a>
. In Rails 7, that is changed to <code>MAILGUN_INGRESS_SIGNING_KEY</code>. So we renamed
the environment variable to fix the problem.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 allows infinite ranges in length validators]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-endless-ranges-for-activemodel-validations"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-endless-ranges-for-activemodel-validations.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-endless-ranges-for-activemodel-validations</id>
      <published>2022-08-30T00:00:00.000Z</published>
      <updated>2022-08-30T00:00:00.000Z</updated>
      <author>
        <name>Ghouse Mohamed</name>
        <uri>https://www.bigbinary.com/blog/authors/ghousemohamed</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-endless-ranges-for-activemodel-validations.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.1 allows infinite ranges for LengthValidators and Clusivity validators]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-endless-ranges-for-activemodel-validations"><![CDATA[<p>Rails 7.1 adds support for infinite ranges for Active Model validations, which
use the <code>:in</code>, and <code>:within</code> options. It was already possible to query using
infinite ranges in Active Record like so:</p>
<pre><code class="language-ruby">Book.where(purchases: 20..)
# Returns a collection of records with purchases from 20 and upwards.
Book.where(purchases: ..20)
# Returns a collection of records with purchases from 20 and below.
</code></pre>
<p>But the same idea of using infinite ranges in Active Model validations was
limited in scope. Rails 7.1 extends this scope of usage by adding support for
infinite ranges in Active Model validations. For example, validating the length
of <code>first_name</code> without an upper bound for a <code>User</code> will be as simple as
writing:</p>
<pre><code class="language-ruby">class User
    # ...
    validates_length_of :first_name, in: 20..
end
</code></pre>
<p>The length of the <code>:first_name</code> does not have an upper bound. As long as the
length is greater than or equal to 20, it will remain valid.</p>
<p>The above example also holds true when using the <code>:within</code> option as well:</p>
<pre><code class="language-ruby">class User
    # ...
    validates_length_of :first_name, within: 20..
end
</code></pre>
<p>In a similar example, let's look at how we would use Active Model validations
along with the <code>:inclusion</code> option:</p>
<pre><code class="language-ruby">class User
    # ...
    validates :age, inclusion: { in: proc { (25..) } }
end
</code></pre>
<p>The above example would validate the <code>:age</code> field such that, it's value needs to
be 25 or above for the record to be valid.</p>
<p>Please check out the following pull requests for more details:</p>
<ol>
<li><a href="https://github.com/rails/rails/pull/45138">Infinite ranges for LengthValidator</a></li>
<li><a href="https://github.com/rails/rails/pull/45123">Infinite ranges for Clusivity validator</a></li>
</ol>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 raises if Active Storage service is missing]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-raises-error-if-active-storage-service-not-specified"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-raises-error-if-active-storage-service-not-specified.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-raises-error-if-active-storage-service-not-specified</id>
      <published>2022-08-23T00:00:00.000Z</published>
      <updated>2022-08-23T00:00:00.000Z</updated>
      <author>
        <name>Ghouse Mohamed</name>
        <uri>https://www.bigbinary.com/blog/authors/ghousemohamed</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-raises-error-if-active-storage-service-not-specified.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.1 raises RuntimeError if Active Storage service is not specified]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-raises-error-if-active-storage-service-not-specified"><![CDATA[<p>If Active Storage has been configured, and the service type has not been
explicitly set in the respective environment's configuration file, then trying
to use active storage throws the following error message:</p>
<pre><code class="language-plaintext">Failed to replace attachments_attachments because one or more of the new records could not be saved.
</code></pre>
<p>This is not helpful, and it doesn't indicate where to make the required changes
for Active Storage to be able to save the attachment(s). It also allows the
application to start as if a valid service has been set for Active Storage to
use. Starting Rails 7.1, if <code>config.active_storage.service</code> has not been
explicitly set, then even attempting to start the application would throw a
<code>RuntimeError</code> with the following error message:</p>
<pre><code class="language-plaintext">Missing Active Storage service name. Specify Active Storage service name for config.active_storage.service in config/environments/production.rb
</code></pre>
<p>Please check out this <a href="https://github.com/rails/rails/pull/44372">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 adds Action Cable connection-level callbacks]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-1-adds-callbacks-for-action-cable-connection"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-adds-callbacks-for-action-cable-connection.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-1-adds-callbacks-for-action-cable-connection</id>
      <published>2022-08-02T00:00:00.000Z</published>
      <updated>2022-08-02T00:00:00.000Z</updated>
      <author>
        <name>Ghouse Mohamed</name>
        <uri>https://www.bigbinary.com/blog/authors/ghousemohamed</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-1-adds-callbacks-for-action-cable-connection.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.1 adds callbacks for Action Cable commands at the connection level]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-1-adds-callbacks-for-action-cable-connection"><![CDATA[<p>Action Cable allows us to add callbacks for individual channels. These are:
<code>after_subscribe</code>, <code>after_unsubscribe</code>, <code>before_subscribe</code>,
<code>before_unsubscribe</code>, <code>on_subscribe</code>, <code>on_unsubscribe</code>. These callbacks are
registered individually for each Channel. Before Rails 7.1, there was no way in
which we could register callbacks to be called before every command generically.
Rails 7.1 solves this problem by providing a set of callbacks that can be
registered at the connection level. And these callbacks are called for every
command, regardless of which channel's command is being invoked.</p>
<p>These are the following callbacks, which can be registered:</p>
<ol>
<li><code>before_command</code>: This callback is invoked before any command can be
processed by the channel.</li>
<li><code>around_command</code>: This callback is generally invoked around the command. Any
piece of code before <code>yield</code> is run before the actual command and any piece
of code after <code>yield</code> is run after the command has been processed by the
channel.</li>
<li><code>after_command</code>: This callback is invoked after the command has been
processed by the channel.</li>
</ol>
<p>Let's take a look at some example code to understand this behaviour better:</p>
<pre><code class="language-ruby">class Connection &lt; ActionCable::Connection::Base
  identified_by :current_user
  before_command :set_current_user
  around_command :register_telemetry_data
  after_command :update_current_user

  private

    def set_current_user
      if request.params[&quot;user_id&quot;].present?
        self.current_user = User.find_by(request.params[&quot;user_id&quot;])
      end
      reject_unauthorized_connection if self.current_user.nil?
    end

    def register_telemetry_data
      self.current_user.register_telemetry({ start: true })
      yield
      self.current_user.register_telemetry({ end: true })
    end

    def update_current_user
      self.current_user.touch(:updated_at)
    end
end
</code></pre>
<p>Here, we can expect <code>set_current_user</code> to be invoked before every command is
processed. Similar to this, we can also expect <code>update_current_user</code> to be
invoked after every command is processed. Whereas for the
<code>register_telemetry_data</code>,
<code>self.current_user.register_telemetry({ start: true })</code> is run before the
command is processed and then after the command is processed,
<code>self.current_user.register_telemetry({ end: true })</code> is run.</p>
<p>Please check out this <a href="https://github.com/rails/rails/pull/44696">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 audio_tag and video_tag accept Active Storage]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-extends-support-for-audio-tag-and-video-tag"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-extends-support-for-audio-tag-and-video-tag.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-extends-support-for-audio-tag-and-video-tag</id>
      <published>2022-07-27T00:00:00.000Z</published>
      <updated>2022-07-27T00:00:00.000Z</updated>
      <author>
        <name>Ghouse Mohamed</name>
        <uri>https://www.bigbinary.com/blog/authors/ghousemohamed</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-extends-support-for-audio-tag-and-video-tag.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.1 allows audio_tag and video_tag to receive Active Storage attachments]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-extends-support-for-audio-tag-and-video-tag"><![CDATA[<p>Rails 7.1 allows <code>audio_tag</code> and <code>video_tag</code> ActionView helpers to receive
Active Storage Attachments which implicitly unpacks the asset path to be
included in the <code>src</code> attribute of the <code>&lt;audio&gt;&lt;/audio&gt;</code> and <code>&lt;video&gt;&lt;/video&gt;</code>
tags.</p>
<p>Previously, the helper methods received only the asset path/url. To get the
asset path of an Active Storage Attachment, we had to explicitly call
<code>polymorphic_path</code> on the attachment, which returned the desired asset path.</p>
<h3>Before</h3>
<pre><code class="language-ruby">audio_tag(polymorphic_path(user.audio_file))
# =&gt; &lt;audio src=&quot;/...&quot;&gt;&lt;/audio&gt;
video_tag(polymorphic_path(user.video_file))
# =&gt; &lt;video src=&quot;/...&quot;&gt;&lt;/video&gt;
</code></pre>
<h3>After</h3>
<pre><code class="language-ruby">audio_tag(user.audio_file)
# =&gt; &lt;audio src=&quot;/...&quot;&gt;&lt;/audio&gt;
video_tag(user.video_file)
# =&gt; &lt;video src=&quot;/...&quot;&gt;&lt;/video&gt;
</code></pre>
<p>Please check out this <a href="https://github.com/rails/rails/pull/44085">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.1 returns Active Storage attachments after save]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-returns-active-storage-blob-after-save"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-returns-active-storage-blob-after-save.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-returns-active-storage-blob-after-save</id>
      <published>2022-07-26T00:00:00.000Z</published>
      <updated>2022-07-26T00:00:00.000Z</updated>
      <author>
        <name>Ghouse Mohamed</name>
        <uri>https://www.bigbinary.com/blog/authors/ghousemohamed</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-returns-active-storage-blob-after-save.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.1 returns the Active Storage attachment(s) after saving the attachment]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-returns-active-storage-blob-after-save"><![CDATA[<p>Previously, saving an attachment to a record returned a boolean, indicating
whether or not the attachment was saved to the record. This is not helpful since
we have to dig into the record again to retrieve the attachment. Starting Rails
7.1, saving an attachment to a record returns the saved attachment. We can now
conveniently use blob methods like <code>#download</code>, <code>#url</code>, <code>#variant</code> etc on the
attachment without having to dig into the record again.</p>
<h3>Before</h3>
<pre><code class="language-ruby"># rails console
&gt;&gt; @user = User.create!(name: &quot;Josh&quot;)
&gt;&gt; @user.avatar.attach(params[:avatar])
=&gt; true
</code></pre>
<h3>After</h3>
<pre><code class="language-ruby"># rails console
&gt;&gt; @user = User.create!(name: &quot;Josh&quot;)
&gt;&gt; @user.avatar.attach(params[:avatar])
=&gt; #&lt;ActiveStorage::Attached::One:0x00007f075e592380 @name=&quot;avatar&quot; @record=#&lt;User:0x00007f075e5924e8 id: &quot;1&quot;, name: &quot;Josh&quot;&gt;
</code></pre>
<p>Please check out this <a href="https://github.com/rails/rails/pull/44439">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds only_numeric option to numericality validator]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-only_numeric-option-to-numericality-validator"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-only_numeric-option-to-numericality-validator.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-only_numeric-option-to-numericality-validator</id>
      <published>2022-01-17T00:00:00.000Z</published>
      <updated>2022-01-17T00:00:00.000Z</updated>
      <author>
        <name>Aditya Bhutani</name>
        <uri>https://www.bigbinary.com/blog/authors/adityabhutani</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-only_numeric-option-to-numericality-validator.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.0.1 introduces onlynumeric option to the numericality validator which specifies whether the value has to be an instance of Numeric. The default behavior is to attempt parsing the value if it...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-only_numeric-option-to-numericality-validator"><![CDATA[<p>Rails 7.0.1 introduces <code>only_numeric</code> option to the numericality validator which
specifies whether the value has to be an instance of Numeric. The default
behavior is to attempt parsing the value if it is a String.</p>
<p>When the database field is a float column, the data will get serialized to the
correct type. In the case of a JSON column, serialization doesn't take place.</p>
<p>As a resolution, Rails 7 has added <code>only_numeric</code> option to numericality
validator.</p>
<p>We will see it in action.</p>
<p>To demonstrate, we need to generate a table that has a json/jsonb column.</p>
<pre><code class="language-ruby"># migration
create_table :users do |t|
  t.jsonb :personal
end
</code></pre>
<h3>Before Validation</h3>
<pre><code class="language-ruby"># Model
class User &lt; ApplicationRecord
  store_accessor :personal, %i[age tooltips]
end
</code></pre>
<pre><code class="language-ruby"># rails console
&gt;&gt; User.create!(age: '29')
=&gt; #&lt;User id: 1, preferences: {&quot;age&quot;=&gt;&quot;29&quot;}, created_at: Sun, 16 Jan 2022 14:09:43.045301000 UTC +00:00, updated_at: Sun, 16 Jan 2022 14:09:43.045301000 UTC +00:00&gt;
</code></pre>
<h3>After Validation</h3>
<pre><code class="language-ruby"># Model
class User &lt; ApplicationRecord
  store_accessor :personal, %i[age tooltips]
  validates_numericality_of :age, only_numeric: true, allow_nil: true
end
</code></pre>
<pre><code class="language-ruby"># rails console
&gt;&gt; User.create!(age: '29')
=&gt; 'raise_validation_error': Validation failed: Age is not a number (ActiveRecord::RecordInvalid)

&gt;&gt; User.create!(age: 29)
=&gt; #&lt;User id: 2, preferences: {&quot;age&quot;=&gt;29}, created_at: Sun, 16 Jan 2022 14:15:44.599934000 UTC +00:00, updated_at: Sun, 16 Jan 2022 14:15:44.599934000 UTC +00:00&gt;
</code></pre>
<p>Please check out this <a href="https://github.com/rails/rails/pull/43914">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds Pathname#existence]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-pathname-existence"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-pathname-existence.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-pathname-existence</id>
      <published>2021-12-07T00:00:00.000Z</published>
      <updated>2021-12-07T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-pathname-existence.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7 introduces Pathname#existence method, which returns the receiver if the given file path exists, otherwise returns nil. Before We need to first check whether the given file path exists or not...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-pathname-existence"><![CDATA[<p>Rails 7 introduces
<a href="https://api.rubyonrails.org/classes/Pathname.html#method-i-existence"><code>Pathname#existence</code></a>
method, which returns the receiver if the given file path exists, otherwise
returns nil.</p>
<h3>Before</h3>
<p>We need to first check whether the given file path exists or not to perform any
other operations on it.</p>
<pre><code class="language-ruby">=&gt; file_path = &quot;config/schedule.yml&quot;
=&gt; Pathname.new(file_path).read if Pathname.new(file_path).exist?
</code></pre>
<h3>Rails 7 onwards</h3>
<p>The <code>Pathname#existence</code> method acts like <code>Object#presence</code> for file existence.</p>
<pre><code class="language-ruby">=&gt; file_path = &quot;config/schedule.yml&quot;
=&gt; Pathname.new(file_path).existence&amp;.read
</code></pre>
<p>Please check out this <a href="https://github.com/rails/rails/pull/43726">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds nested attributes support to delegated_type]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-accepts-nested-attributes-for-support-for-delegated_type"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-accepts-nested-attributes-for-support-for-delegated_type.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-accepts-nested-attributes-for-support-for-delegated_type</id>
      <published>2021-11-23T00:00:00.000Z</published>
      <updated>2021-11-23T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-accepts-nested-attributes-for-support-for-delegated_type.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7 adds accepts_nested_attributes_for support for delegated_type]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-accepts-nested-attributes-for-support-for-delegated_type"><![CDATA[<p>Rails 6.1 introduced the <code>delegated_type</code> to Active Record, which makes it easier
for models to share responsibilities. Please see our
<a href="https://www.bigbinary.com/blog/rails-6-1-adds-delegated-type-to-active-record">blog</a>
to read more about <code>delegated_type</code>.</p>
<pre><code class="language-ruby">class Entry &lt; ApplicationRecord
  # Schema
  #  entryable_type, entryable_id, ...
  delegated_type :entryable, types: %w[ Message Comment ]
end

class Message
  # Schema
  #  subject, ...
end

class Comment
  # Schema
    #  content, ...
end
</code></pre>
<p>The <code>accepts_nested_attributes_for</code> option is very helpful while handling nested
forms. We can easily create and update associated records by passing details
along with the main object parameters when the <code>accepts_nested_attributes_for</code>
option is enabled.</p>
<h3>Before</h3>
<p>The <code>accepts_nested_attributes_for</code> option is not available for
<code>delegated_type</code>, hence we can't use nested forms for associated objects
configured via <code>delegated_type</code>.</p>
<h3>Rails 7 onwards</h3>
<p>Rails 7 adds <code>accepts_nested_attributes_for</code> support to <code>delegated_type</code>, which
allows to create and update records easily without needing to write specific
methods or logic.</p>
<pre><code class="language-ruby">class Entry &lt; ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ]
  accepts_nested_attributes_for :entryable
end

params = {
  entry: {
    entryable_type: 'Message',
    entryable_attributes: { subject: 'Delegated Type' }
  }
}

message_entry = Entry.create(params[:entry])

params = {
  entry: {
    entryable_type: 'Comment',
    entryable_attributes: { content: 'Looks Cool!' }
  }
}

comment_entry = Entry.create(params[:entry])
</code></pre>
<p>If we want to deal with more logic or validations while creating the entryable
objects, we'll have to create a method specifically and do the logic there.</p>
<pre><code class="language-ruby">class Entry &lt; ApplicationRecord
  def self.create_with_comment(content)
    # Validation logic goes here
    create! entryable: Comment.new(content: content)
  end
end
</code></pre>
<p>Please check out this <a href="https://github.com/rails/rails/pull/41717">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds from option to assert_no_changes]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-from-option-to-assert_no_changes"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-from-option-to-assert_no_changes.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-from-option-to-assert_no_changes</id>
      <published>2021-11-19T00:00:00.000Z</published>
      <updated>2021-11-19T00:00:00.000Z</updated>
      <author>
        <name>Gaurav Varma</name>
        <uri>https://www.bigbinary.com/blog/authors/gaurav-varma</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-from-option-to-assert_no_changes.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7 Adds from option to ActiveSupport::TestCase#assert_no_changes]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-from-option-to-assert_no_changes"><![CDATA[<p>Rails
<a href="https://guides.rubyonrails.org/active_support_core_extensions.html">Active Support</a>
provides various extensions, utilities, and helpers. It provides a collection of
utility classes and standard library extensions that are very useful.</p>
<p>Rails 5.1 introduced <code>assert_no_changes</code> and <code>assert_changes</code>, making it easier
to observe changes. Using
<a href="https://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#method-i-assert_no_changes">ActiveSupport::TestCase#assert_no_changes</a>
we can easily assert that the result of evaluating an expression has not changed
before and after calling the passed block.</p>
<p>To assert the expected change in the value of an object, we can use
<code>assert_changes</code>.</p>
<pre><code class="language-ruby">assert_changes -&gt; { user.address } do
  user.update address: 'Miami'
end
</code></pre>
<p><code>assert_changes</code> also supports <code>from</code> and <code>to</code> options.</p>
<pre><code class="language-ruby">assert_changes -&gt; { user.address }, from: 'San Francisco', to: 'Miami' do
  user.update address: 'Miami'
end
</code></pre>
<p>Similarly, <code>assert_no_changes</code> allows us to assert a value that is expected to
not change.</p>
<pre><code class="language-ruby">assert_no_changes -&gt; { user.address } do
  user.update address: 'Miami'
end
</code></pre>
<p>We can also specify an error message with <code>assert_no_changes</code>.</p>
<pre><code class="language-ruby">assert_no_changes -&gt; { user.address }, 'Expect the address to not change' do
  user.update address: 'Miami'
end
</code></pre>
<h3>Before</h3>
<p><code>assert_no_changes</code> did not support the <code>from</code> option, similar to
<code>assert_changes</code>.</p>
<pre><code class="language-ruby">assert_no_changes -&gt; { user.address } do
  user.update address: 'Miami'
end
</code></pre>
<p>However,
<a href="https://github.com/rails/rails/pull/42277">Rails 7 has added from: option to ActiveSupport::TestCase#assert_no_changes</a>,
allowing us to assert on the initial value that is expected to not change.</p>
<h3>Rails 7 onwards</h3>
<p>Provides the optional <code>from</code> argument to specify the expected initial value.</p>
<pre><code class="language-ruby">assert_no_changes -&gt; { user.address }, from: 'San Francisco' do
  user.update address: 'Miami'
end
</code></pre>
<p>Check out this <a href="https://github.com/rails/rails/pull/42277">pull request</a> for
more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 replaced byebug with ruby/debug]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-replaced-byebug-with-ruby-debug"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-replaced-byebug-with-ruby-debug.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-replaced-byebug-with-ruby-debug</id>
      <published>2021-11-09T00:00:00.000Z</published>
      <updated>2021-11-09T00:00:00.000Z</updated>
      <author>
        <name>Gaurav Varma</name>
        <uri>https://www.bigbinary.com/blog/authors/gaurav-varma</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-replaced-byebug-with-ruby-debug.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 5 introduced byebug which is an easy-to-use, feature-rich ruby debugger. It offers features like Stepping, Breaking, Evaluating, Tracking. Using byebug we can easily control the execution of a...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-replaced-byebug-with-ruby-debug"><![CDATA[<p>Rails 5 introduced <a href="https://github.com/deivid-rodriguez/byebug">byebug</a> which is
an easy-to-use, feature-rich ruby debugger. It offers features like <code>Stepping</code>,
<code>Breaking</code>, <code>Evaluating</code>, <code>Tracking</code>.</p>
<p>Using <a href="https://github.com/deivid-rodriguez/byebug">byebug</a> we can easily control
the execution of a program and the debug inspector for call stack navigation.
This allows us to handle and track the execution flow.</p>
<p>Here is
<a href="https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-byebug-gem">byebug documentation</a>
and here is the <a href="https://github.com/rails/rails/pull/14646">pull request</a> where
it was added.</p>
<p><a href="https://github.com/rails/rails/pull/43187">Rails 7 is replacing byebug with ruby/debug</a>.
<code>debug</code> is Ruby’s new debugger, which will be included in Ruby 3.1. To align
Rails with Ruby <code>debug</code> has been added to Rails 7.</p>
<p>Let's see an example of debugging with both Byebug and Debug.</p>
<h3>Before</h3>
<p>Let's assume we have a <code>NameController</code>. Inside any Rails application, you can
call the debugger by calling the <code>byebug</code> method.</p>
<pre><code class="language-ruby"># app/controllers/name_controller.rb
class NameController &lt; ApplicationController
  def index
    name = &quot;John Doe&quot;
    byebug # Call to debugger
    city = &quot;San Francisco&quot;
  end
end
</code></pre>
<p>Then the invoked debugger results in the following.</p>
<pre><code class="language-ruby">    [1, 7] in app/controllers/test_controller.rb
    1: class NameController &lt; ApplicationController
    2:   def index
    3:     name = &quot;John Doe&quot;
    4:     byebug # Call to debugger
=&gt;  5:    city = &quot;San Francisco&quot;
    6:   end
    7: end

  (byebug) name # variable call
  &quot;John Doe&quot;
</code></pre>
<h3>Rails 7 onwards</h3>
<p>We can use the <code>binding.break</code> method for calling Ruby Debug.</p>
<pre><code class="language-ruby"># app/controllers/name_controller.rb
class NameController &lt; ApplicationController
  def index
    name = &quot;John Doe&quot;
    binding.break # Call to debugger
    city = &quot;San Francisco&quot;
  end
end
</code></pre>
<p>The invoked debugger results in the following.</p>
<pre><code class="language-ruby">  [1, 7] in app/controllers/test_controller.rb
  1| class NameController &lt; ApplicationController
  2|   def index
  3|     name = &quot;John Doe&quot;
  4|     binding.break # Call to debugger
&gt; 5|    city = &quot;San Francisco&quot;
  6|   end
  7| end
&gt;#0 NameController#index at ~/demo_app/app/controllers/name_controller.rb:5
  #1  ActionController::BasicImplicitRender#send_action(method=&quot;index&quot;, args=[])
(rdbg) name # variable call
&quot;John Doe&quot;
</code></pre>
<p>Check out this <a href="https://github.com/rails/rails/pull/43187">pull request</a> for
more details and for commands or features of Ruby Debug, please visit
<a href="https://github.com/ruby/debug">Ruby-Debug</a>.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds weekday_options_for_select and weekday_select]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-weekday_options_for_select-and-weekday_select"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-weekday_options_for_select-and-weekday_select.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-weekday_options_for_select-and-weekday_select</id>
      <published>2021-11-09T00:00:00.000Z</published>
      <updated>2021-11-09T00:00:00.000Z</updated>
      <author>
        <name>Gaurav Varma</name>
        <uri>https://www.bigbinary.com/blog/authors/gaurav-varma</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-weekday_options_for_select-and-weekday_select.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[In web applications, forms are one of the most essential interfaces for user input, and it can be tedious to write and maintain form markups with many attributes. Rails provide Action View Form...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-weekday_options_for_select-and-weekday_select"><![CDATA[<p>In web applications, forms are one of the most essential interfaces for user
input, and it can be tedious to write and maintain form markups with many
attributes. Rails provide
<a href="https://guides.rubyonrails.org/form_helpers.html">Action View Form Helpers</a> for
generating form markup.</p>
<p>Using
<a href="https://guides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease">select</a>
helper we can easily create select boxes in HTML with one <code>&lt;option&gt;</code> element for
each option to choose from.</p>
<p>For example, let's say we have a list of cities for the user to choose from.</p>
<pre><code class="language-ruby"># app/views/address/new.html.erb
&lt;%= form.select :city, [&quot;Pune&quot;, &quot;Mumbai&quot;, &quot;Delhi&quot;] %&gt;
</code></pre>
<p>Rails will generate the following markup.</p>
<pre><code class="language-html">&lt;select name=&quot;city&quot; id=&quot;city&quot;&gt;
  &lt;option value=&quot;Pune&quot;&gt;Pune&lt;/option&gt;
  &lt;option value=&quot;Mumbai&quot;&gt;Mumbai&lt;/option&gt;
  &lt;option value=&quot;Delhi&quot;&gt;Delhi&lt;/option&gt;
&lt;/select&gt;
</code></pre>
<p>Previously for generating a select box for weekday select, we needed to write a
custom helper. Rails did not have anything out of the box for the weekday
selection.</p>
<p>However,
<a href="https://github.com/rails/rails/pull/42979">Rails 7 has added weekday_options_for_select and weekday_select</a>
using which we can easily generate a dropdown field of selecting a weekday.</p>
<h3>Before</h3>
<p>In Rails 6.1, we can create a dropdown field for weekdays as shown here.</p>
<pre><code class="language-ruby"># app/views/users/new.html.erb
&lt;%= form_with(model: user) do |form| %&gt;
  &lt;div class=&quot;field&quot;&gt;
    &lt;%= form.label :weekly_off %&gt;
    &lt;%= form.select :weekly_off, I18n.t('date.day_names') %&gt;
  &lt;/div&gt;
&lt;% end %&gt;
</code></pre>
<p>Or we can do something like this.</p>
<pre><code class="language-ruby"># app/views/users/new.html.erb
&lt;%= form_with(model: user) do |form| %&gt;
  &lt;div class=&quot;field&quot;&gt;
    &lt;%= form.label :weekly_off %&gt;
    &lt;%= form.select :weekly_off, I18n.t('date.day_names').map.with_index.to_h %&gt;
  &lt;/div&gt;
&lt;% end %&gt;
</code></pre>
<p>Then the generated markup looks like this.</p>
<pre><code class="language-html">&lt;select name=&quot;user[weekly_off]&quot; id=&quot;user_weekly_off&quot;&gt;
  &lt;option value=&quot;Sunday&quot;&gt;Sunday&lt;/option&gt;
  &lt;option value=&quot;Monday&quot;&gt;Monday&lt;/option&gt;
  &lt;option value=&quot;Tuesday&quot;&gt;Tuesday&lt;/option&gt;
  &lt;option value=&quot;Wednesday&quot;&gt;Wednesday&lt;/option&gt;
  &lt;option value=&quot;Thursday&quot;&gt;Thursday&lt;/option&gt;
  &lt;option value=&quot;Friday&quot;&gt;Friday&lt;/option&gt;
  &lt;option value=&quot;Saturday&quot;&gt;Saturday&lt;/option&gt;
&lt;/select&gt;
</code></pre>
<p>Here is how it would look if we go with the second option.</p>
<pre><code class="language-html">&lt;select name=&quot;user[weekly_off]&quot; id=&quot;user_weekly_off&quot;&gt;
  &lt;option value=&quot;0&quot;&gt;Sunday&lt;/option&gt;
  &lt;option value=&quot;1&quot;&gt;Monday&lt;/option&gt;
  &lt;option value=&quot;2&quot;&gt;Tuesday&lt;/option&gt;
  &lt;option value=&quot;3&quot;&gt;Wednesday&lt;/option&gt;
  &lt;option value=&quot;4&quot;&gt;Thursday&lt;/option&gt;
  &lt;option value=&quot;5&quot;&gt;Friday&lt;/option&gt;
  &lt;option value=&quot;6&quot;&gt;Saturday&lt;/option&gt;
&lt;/select&gt;
</code></pre>
<h3>Rails 7 onwards</h3>
<p>We can use the <code>weekday_options_for_select</code> or <code>weekday_select</code> helper for
generating a dropdown field for selecting a weekday.</p>
<pre><code class="language-ruby"># app/views/users/new.html.erb
&lt;%= form_with(model: user) do |form| %&gt;
  &lt;div class=&quot;field&quot;&gt;
    &lt;%= form.label :weekly_off %&gt;
    &lt;%= form.select :weekly_off, weekday_options_for_select(&quot;Monday&quot;, day_format: :abbr_day_names) %&gt;
  &lt;/div&gt;
&lt;% end %&gt;
</code></pre>
<p>Or we can do something like this.</p>
<pre><code class="language-ruby"># app/views/users/new.html.erb
&lt;%= form_with(model: user) do |form| %&gt;
  &lt;div class=&quot;field&quot;&gt;
    &lt;%= form.label :weekly_off %&gt;
    &lt;%= form.weekday_select :weekly_off, { selected: &quot;Monday&quot;, day_format: :abbr_day_names } %&gt;
  &lt;/div&gt;
&lt;% end %&gt;
</code></pre>
<p>Then The generated markup looks like this.</p>
<pre><code class="language-html">&lt;select name=&quot;user[weekly_off]&quot; id=&quot;user_weekly_off&quot;&gt;
  &lt;option value=&quot;Sunday&quot;&gt;Sunday&lt;/option&gt;
  &lt;option selected=&quot;selected&quot; value=&quot;Monday&quot;&gt;Monday&lt;/option&gt;
  &lt;option value=&quot;Tuesday&quot;&gt;Tuesday&lt;/option&gt;
  &lt;option value=&quot;Wednesday&quot;&gt;Wednesday&lt;/option&gt;
  &lt;option value=&quot;Thursday&quot;&gt;Thursday&lt;/option&gt;
  &lt;option value=&quot;Friday&quot;&gt;Friday&lt;/option&gt;
  &lt;option value=&quot;Saturday&quot;&gt;Saturday&lt;/option&gt;
&lt;/select&gt;
</code></pre>
<p><code>weekday_options_for_select</code> accepts a few options and all of them have a
default value.</p>
<p><code>selected</code> defaults to nil and if we provide this argument, the value passed will
be used as the selected option.</p>
<pre><code class="language-html"> &lt;!-- weekday_options_for_select(&quot;Friday&quot;) --&gt;
&lt;option value=\&quot;Sunday\&quot;&gt;Sunday&lt;/option&gt;\n
&lt;option value=\&quot;Monday\&quot;&gt;Monday&lt;/option&gt;\n
&lt;option value=\&quot;Tuesday\&quot;&gt;Tuesday&lt;/option&gt;\n
&lt;option value=\&quot;Wednesday\&quot;&gt;Wednesday&lt;/option&gt;\n
&lt;option value=\&quot;Thursday\&quot;&gt;Thursday&lt;/option&gt;\n
&lt;option selected=\&quot;selected\&quot; value=\&quot;Friday\&quot;&gt;Friday&lt;/option&gt;\n
&lt;option value=\&quot;Saturday\&quot;&gt;Saturday&lt;/option&gt;&quot;
</code></pre>
<p><code>index_as_value</code> defaults to false and if true it will set the value of each
option to the index of that day.</p>
<pre><code class="language-html">&lt;!-- weekday_options_for_select(index_as_value: true) --&gt;
&lt;option value=\&quot;0\&quot;&gt;Sunday&lt;/option&gt;\n
&lt;option value=\&quot;1\&quot;&gt;Monday&lt;/option&gt;\n
&lt;option value=\&quot;2\&quot;&gt;Tuesday&lt;/option&gt;\n
&lt;option value=\&quot;3\&quot;&gt;Wednesday&lt;/option&gt;\n
&lt;option value=\&quot;4\&quot;&gt;Thursday&lt;/option&gt;\n
&lt;option value=\&quot;5\&quot;&gt;Friday&lt;/option&gt;\n
&lt;option value=\&quot;6\&quot;&gt;Saturday&lt;/option&gt;&quot;
</code></pre>
<p><code>day_format</code> defaults to :day_names and passing this a different <code>I18n</code> key will
use different formats for the option display names and their values.</p>
<pre><code class="language-html">&lt;!-- weekday_options_for_select(day_format: :abbr_day_names) --&gt;
&lt;option value=\&quot;Sun\&quot;&gt;Sun&lt;/option&gt;\n
&lt;option value=\&quot;Mon\&quot;&gt;Mon&lt;/option&gt;\n
&lt;option value=\&quot;Tue\&quot;&gt;Tue&lt;/option&gt;\n
&lt;option value=\&quot;We\&quot;&gt;Wedn&lt;/option&gt;\n
&lt;option value=\&quot;Thu\&quot;&gt;Thu&lt;/option&gt;\n
&lt;option value=\&quot;Fri\&quot;&gt;Fri&lt;/option&gt;\n
&lt;option value=\&quot;Sat\&quot;&gt;Sat&lt;/option&gt;&quot;
</code></pre>
<p>Note that <code>:abbr_day_names</code> options are built into Rails, but we can define your
array.</p>
<p>Check out this <a href="https://github.com/rails/rails/pull/42979">pull request</a> for
more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds ActiveRecord::Base#previously_persisted?]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-activerecord-previously_persisted"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-activerecord-previously_persisted.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-activerecord-previously_persisted</id>
      <published>2021-11-09T00:00:00.000Z</published>
      <updated>2021-11-09T00:00:00.000Z</updated>
      <author>
        <name>Gaurav Varma</name>
        <uri>https://www.bigbinary.com/blog/authors/gaurav-varma</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-activerecord-previously_persisted.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Active Record in Rails provides various methods like exists?, persisted?, destroyed? and many more. Using these methods we can easily determine if an object exists in the database or if an object is...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-activerecord-previously_persisted"><![CDATA[<p><a href="https://api.rubyonrails.org/v6.1.4/classes/ActiveRecord/Persistence.html">Active Record</a>
in Rails provides various methods like <code>exists?</code>, <code>persisted?</code>, <code>destroyed?</code> and
many more. Using these methods we can easily determine if an object exists in
the database or if an object is an existing record in the database and not a new
record.</p>
<p>Using these methods we can quickly determine the state of an object and easily
write complex conditional statements that depend on the state of an object.
Previously we did not have a method that lets us determine if an object was a
part of the database in past but now does not exist.</p>
<p>However,
<a href="https://github.com/rails/rails/pull/42389">Rails 7 has added previously_persisted? method to ActiveRecord</a>,
which returns <code>true</code> if an object has been previously a part of the database
records but now has been destroyed.</p>
<p>Let’s assume we have a <code>User</code> model with the name column value <code>John Doe</code>. If
this record has been deleted from the database, we can still check if <code>John Doe</code>
was a user of our app or not in the past.</p>
<h3>Before</h3>
<p>Let's say we delete the user with the name <code>John Doe</code>.</p>
<pre><code class="language-ruby"># app/controllers/user_controller.rb
previous_user = User.find_by_name('John Doe')
previous_user.destroy!
</code></pre>
<p>Now we can check if the user exists in our database.</p>
<pre><code class="language-ruby"># app/controllers/user_controller.rb
# check if previous_user is destroyed and is not a new user
if previous_user.destroyed? &amp;&amp; !previous_user.new_record?
  # returns true
end
</code></pre>
<h3>Rails 7 onwards</h3>
<p>We can use the <code>previously_persisted?</code> method on an object.</p>
<p>Let's delete the user with the name <code>John Doe</code>.</p>
<pre><code class="language-ruby"># app/controllers/user_controller.rb
previous_user = User.find_by_name('John Doe')
previous_user.destroy!
</code></pre>
<p>Now we can check if the user exists in our database using the
<code>previously_persisted?</code> method.</p>
<pre><code class="language-ruby"># app/controllers/user_controller.rb
previous_user.previously_persisted? # returns true
</code></pre>
<p>Check out this <a href="https://github.com/rails/rails/pull/42389">pull request</a> for
more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds ActiveRecord::QueryMethods#in_order_of]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-activerecord-query-methods-in-order-of"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-activerecord-query-methods-in-order-of.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-activerecord-query-methods-in-order-of</id>
      <published>2021-11-02T00:00:00.000Z</published>
      <updated>2021-11-02T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-activerecord-query-methods-in-order-of.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Ruby 7.0 adds ActiveRecord::QueryMethods#in_order_of]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-activerecord-query-methods-in-order-of"><![CDATA[<p>Rails 7 introduces
<a href="https://edgeapi.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-in_order_of">ActiveRecord::QueryMethods#in_order_of</a>
to fetch active record collection in a specific order based on the given
attribute values.</p>
<p>We can see the similar method available for <code>Enumerable#in_order_of</code> to
constrain records in a specific order from an enumerable collection by using
key-series pair. You can find more details here in
<a href="https://www.bigbinary.com/blog/rails-7-adds-enumerable-in-order-of">our blog</a>
regarding <code>Enumerable#in_order_of</code> method.</p>
<p>The newly introduced method is highly helpful to build queries by which we can
specify an explicit order that we would like to get the collection as result.
Otherwise we will have to make custom <code>CASE</code> statements to specify the order in
raw SQL statement format.</p>
<pre><code class="language-ruby"># Fetch Post records in order of [3, 5, 1]
SELECT &quot;posts&quot;.* FROM &quot;posts&quot; ORDER BY CASE &quot;posts&quot;.&quot;id&quot; WHEN 3 THEN 1 WHEN 5 THEN 2 WHEN 1 THEN 3 ELSE 4 END ASC
</code></pre>
<h3>Before</h3>
<p>Suppose we have a <code>Course</code> model with <code>status</code> column having possible values
like <code>enrolled</code>, <code>started</code> &amp; <code>completed</code>. If we want to fetch all course records
as a collection with status values in order of <code>started</code>, <code>enrolled</code> &amp;
<code>completed</code>, then the only option here is to build the <code>CASE</code> statement as raw
SQL. Otherwise we will have to make iterations over the returned result to
modify in the specific order we wish to get back.</p>
<pre><code class="language-ruby">Course.order(
  Arel.sql(
    %q(
      case status
      when 'started' then 1
      when 'enrolled' then 2
      when 'completed' then 3
      else 4 end
    )
  )
)
</code></pre>
<h3>Rails 7 onwards</h3>
<p>The <code>ActiveRecord::QueryMethods#in_order_of</code> method will prepare either <code>CASE</code>
statement or will make use of built-in function (Eg: <code>FIELD</code> in MySQL) based on
the adapter to perform the specified order.</p>
<pre><code class="language-ruby">Course.in_order_of(:status, %w(started enrolled completed))
</code></pre>
<p>The returned result here is an <code>ActiveRecord::Relation</code> object, unlike the result
for <code>Enumerable#in_order_of</code> where it is an array. Henc,e we can chain other
scopes or query methods with the result while using
<code>ActiveRecord::QueryMethods#in_order_of</code> method.</p>
<pre><code class="language-ruby">Course.in_order_of(:status, %w(started enrolled completed)).order(:created_at: :desc).pluck(:name)
</code></pre>
<p>Please check out this <a href="https://github.com/rails/rails/pull/42061">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds disable_joins for associations]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-disable-joins-for-associations"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-disable-joins-for-associations.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-disable-joins-for-associations</id>
      <published>2021-10-26T00:00:00.000Z</published>
      <updated>2021-10-26T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-disable-joins-for-associations.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Ruby 7.0 adds disable_joins for associations]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-disable-joins-for-associations"><![CDATA[<p>Rails 7 introduces <code>disable_joins</code> for database associations to avoid join
errors in multi-tenant applications where the two tables are located in
different database clusters.</p>
<p>Rails commonly performs lazy loading while fetching records for better efficiency
and internally build join queries to fetch the records faster.</p>
<p>But when we deal with different database clusters within the same application,
the lazy loading nature of Active Record causes errors when the databases can't
perform join queries between different clusters.</p>
<p>As a resolution for this, Rails 7 has newly added 'disable_joins' option to tell
Rails upfront that queries must be performed without joining tables. In
this case two or more queries will be generated and used to fetch the results
from different database clusters.</p>
<p>The <code>disable_joins</code> option is available for both <code>has_many :through</code> and
<code>has_one :through</code> associations. In some cases, if order or limit is applied, it
will be performed in-memory due to database limitations.</p>
<pre><code class="language-ruby">class Employee
  has_many :projects
  has_many :tasks, through: :projects, disable_joins: true
end

class Project
  belongs_to :employee
  has_many :tasks
end

class Task
  belongs_to :project
end
</code></pre>
<p>Before Rails 7, <code>@employee.tasks</code> without <code>disable_joins</code> option will raise
error because database clusters can't handle join queries here. If we provide
the <code>disable_joins</code> option as true (by default, the value is set to false) then
Rails will make two or more separate queries to fetch the results from different
database clusters.</p>
<pre><code class="language-sql">SELECT &quot;project&quot;.&quot;id&quot; FROM &quot;projects&quot; WHERE &quot;projects&quot;.&quot;employee_id&quot; = ? [[&quot;employee_id&quot;, 1]]
SELECT &quot;tasks&quot;.* FROM &quot;tasks&quot; WHERE &quot;tasks&quot;.&quot;project_id&quot; IN (?, ?, ?) [[&quot;project_id&quot;, 1], [&quot;project_id&quot;, 2], [&quot;project_id&quot;, 3]]
</code></pre>
<p>Similarly, for has_one through association:</p>
<pre><code class="language-ruby">class Publisher
  has_one :author
  has_one :book, through: :author, disable_joins: true
end

class Author
  belongs_to :publisher
  has_one :book
end

class Book
  belongs_to :author
end
</code></pre>
<p>The <code>@publisher.book</code> will make the following two queries to fetch the results.</p>
<pre><code class="language-sql">SELECT &quot;author&quot;.&quot;id&quot; FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;publisher_id&quot; = ? [[&quot;publisher_id&quot;, 1]]
SELECT &quot;books&quot;.* FROM &quot;books&quot; WHERE &quot;books&quot;.&quot;author_id&quot; = ? [[&quot;author_id&quot;, 1]]
</code></pre>
<p>Please be aware that enabling this option without realizing the actual need will
result in performance implications since two or more queries are performed here.
Also queries with order or limit will be done in-memory since the order from one
database can't be applied to another database query.</p>
<p>Please check out the <code>disable_joins</code> pull requests for
<a href="https://github.com/rails/rails/pull/41937">has_many through</a> &amp;
<a href="https://github.com/rails/rails/pull/42079">has_one through</a> associations for
more details and discussions.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds the ability to use pre-defined variants]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-ability-to-use-predefined-variants"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-ability-to-use-predefined-variants.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-ability-to-use-predefined-variants</id>
      <published>2021-10-19T00:00:00.000Z</published>
      <updated>2021-10-19T00:00:00.000Z</updated>
      <author>
        <name>Gaurav Varma</name>
        <uri>https://www.bigbinary.com/blog/authors/gaurav-varma</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-ability-to-use-predefined-variants.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 5.2 introduced ActiveStorage which made it possible to easily upload files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage. It also helped in...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-ability-to-use-predefined-variants"><![CDATA[<p>Rails 5.2 introduced
<a href="https://guides.rubyonrails.org/active_storage_overview.html">ActiveStorage</a>
which made it possible to easily upload files to a cloud storage service like
Amazon S3, Google Cloud Storage, or Microsoft Azure Storage. It also helped in
attaching the files to active record objects.</p>
<p>Using <code>ActiveStorage</code> and <a href="https://www.imagemagick.org">ImageMagick</a> we can
transform image uploads and extract metadata from files. For transforming image
uploads we can use <a href="https://www.imagemagick.org">image_processing</a> gem with
<code>ActiveStorage</code> and create variants of an image.</p>
<p>Previously for creating image variants, we needed to use
<a href="https://www.imagemagick.org">image_processing</a> gem with <code>ActiveStorage</code>
processor. The default processor for <code>ActiveStorage</code> is <code>MiniMagick</code>, but we can
also use <a href="https://www.rubydoc.info/gems/ruby-vips/Vips/Image">Vips</a>.</p>
<p>However,
<a href="https://github.com/rails/rails/pull/39135">Rails 7 has added the ability to use pre-defined variants</a>
which provides a way to easily create variants for images.</p>
<p>Let's assume we have a model <code>Blog</code>. Using <code>has_one_attched</code> every record can
have one file attached to it.</p>
<pre><code class="language-ruby"># app/models/blog.rb
class Blog &lt; ApplicationRecord
  has_one_attached :display_picture # Setup mapping between record and file
end
</code></pre>
<p>To create a <code>blog</code> with an attachment on <code>display_picture</code>.</p>
<pre><code class="language-ruby"># app/views/blogs/new.html.erb
&lt;%= form.file_field :avatar %&gt;
</code></pre>
<pre><code class="language-ruby"># app/controllers/blogs_controller.rb
class BlogsController &lt; ApplicationController
  def create
    blog = Blog.create!(blog_params)
    session[:user_id] = blog.id
    redirect_to root_path
  end

  private
    def blog_params
      params.require(:blog).permit(:title, :display_picture)
    end
end
</code></pre>
<h3>Before</h3>
<p>If we want to create variants of <code>display_picture</code>, we need to add the
<a href="https://www.imagemagick.org">image_processing</a> gem to the <code>Gemfile</code>.</p>
<pre><code class="language-ruby"># project_folder/Gemfile
gem 'image_processing'
</code></pre>
<p>Then, to create variants of the image, we can call the <code>variant</code> method on the
attachment record.</p>
<pre><code class="language-ruby"># app/views/blogs/show.html.erb
&lt;%= image_tag blog.display_picture.variant(resize_to_limit: [100, 100]) %&gt;
</code></pre>
<h3>Rails 7 onwards</h3>
<p>We can use the <code>variants</code> option on <code>has_one_attached</code>.</p>
<pre><code class="language-ruby">class Blog &lt; ActiveRecord::Base
  has_one_attached :display_picture, variants: {
    thumb: { resize: &quot;100x100&quot; },
    medium: { resize: &quot;300x300&quot; }
  }
end
</code></pre>
<p>To display we can use the <code>variant</code> method.</p>
<pre><code class="language-ruby"># app/views/blogs/show.html.erb
&lt;%= image_tag blog.display_picture.variant(:thumb) %&gt;
</code></pre>
<p><code>variants</code> can also be used on <code>has_many_attached</code>. Check out this
<a href="https://github.com/rails/rails/pull/39135">pull request</a> for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds a setting to enumerate columns in select]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-setting-for-enumerating-columns-in-select-statements"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-setting-for-enumerating-columns-in-select-statements.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-setting-for-enumerating-columns-in-select-statements</id>
      <published>2021-10-13T00:00:00.000Z</published>
      <updated>2021-10-13T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-setting-for-enumerating-columns-in-select-statements.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Ruby 7.0 adds setting for enumerating columns in select statements]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-setting-for-enumerating-columns-in-select-statements"><![CDATA[<p>Rails 7 has introduced a new setting called
<code>enumerate_columns_in_select_statements</code> for enumerating columns in ActiveRecord
select query statements by which we can avoid common
<a href="https://apidock.com/rails/ActiveRecord/PreparedStatementCacheExpired">ActiveRecord::PreparedStatementCacheExpired</a>
errors.</p>
<p>Rails uses prepared statements for database query efficiency. When prepared
statements are being used, the repeated queries will be cached based on the
prepared statement query plan at the Postgres database level. This cached value will
become invalid when the returned results are changed.</p>
<p>Whenever we make any schema changes to the database tables while the application is
running, the cached select statements with a wildcard column definition will raise
<code>PreparedStatementCacheExpired</code> error since the query output has modified.</p>
<h3>Before</h3>
<pre><code class="language-ruby">=&gt; User.limit(10)
=&gt; SELECT * FROM users LIMIT 10
</code></pre>
<p>If we use the select query with <code>*</code>, then any change in the database schema for
the particular table (eg: users) will invalidate the prepared statement cache
and result in the <code>PreparedStatementCacheExpired</code> error. The solution here is to
mention the columns explicitly in the select statement as shown below:</p>
<pre><code class="language-ruby">=&gt; SELECT &quot;first_name,last_name,email ...&quot; FROM users LIMIT 10
</code></pre>
<h3>Rails 7 onwards</h3>
<p>Rails 7 adds a new setting by which we can ensure all select statements are
generated by enumerating the columns explicitly. Hence, any modifications to the
database schema won't result in <code>PreparedStatementCacheExpired</code>, instea,d the
prepared statements will be changed and the respective query will be cached
freshly by the Postgres database.</p>
<p>We can either configure the setting for all models or at a specific model level.</p>
<pre><code class="language-ruby"># config/application.rb
module MyApp
  class Application &lt; Rails::Application
    config.active_record.enumerate_columns_in_select_statements = true
  end
end

# User model specific
class User &lt; ApplicationRecord
  self.enumerate_columns_in_select_statements = true
end
</code></pre>
<p>When the setting value is set to <code>true</code> the select statement will always
contains columns explicitly.</p>
<pre><code class="language-ruby">=&gt; User.limit(10)
=&gt; SELECT &quot;first_name,last_name,email ...&quot; FROM users LIMIT 10
</code></pre>
<p>Check out this <a href="https://github.com/rails/rails/pull/41718">pull request</a> for
more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds ComparisonValidator to ActiveRecord]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-comparison-validator-to-active-record"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-comparison-validator-to-active-record.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-comparison-validator-to-active-record</id>
      <published>2021-10-05T00:00:00.000Z</published>
      <updated>2021-10-05T00:00:00.000Z</updated>
      <author>
        <name>Gaurav Varma</name>
        <uri>https://www.bigbinary.com/blog/authors/gaurav-varma</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-comparison-validator-to-active-record.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Ruby 7.0 adds ComparisonValidator to ActiveRecord]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-comparison-validator-to-active-record"><![CDATA[<p>Rails
<a href="https://guides.rubyonrails.org/active_record_validations.html">Active Record Validation</a>
provides a convenient way to validate the state of an object before it is stored
in the database. There are various built-in
<a href="https://guides.rubyonrails.org/active_record_validations.html">Active Record validations</a>
like <code>presence</code>, <code>length</code>, <code>numericality</code> and <code>uniqueness</code>.</p>
<p>By using
<a href="https://guides.rubyonrails.org/active_record_validations.html#numericality">numericality validator</a>,
we can validate an attribute to only have numeric values.</p>
<pre><code class="language-ruby"># app/models/blog.rb
class Blog &lt; ApplicationRecord
  validates :likes, numericality: true
end
</code></pre>
<p>We can also use helpers like <code>greater_than</code>, <code>greater_than_or_equal_to</code>,
<code>equal_to</code>, <code>less_than</code>, <code>less_than_or_equal_to</code>, <code>other_than</code>, <code>odd</code>, <code>even</code>
with
<a href="https://guides.rubyonrails.org/active_record_validations.html#numericality">numericality validator</a>
but these work only on numbers.</p>
<pre><code class="language-ruby"># app/models/blog.rb
class Blog &lt; ApplicationRecord
  validates :likes, numericality: { greater_than: 1 }
end
</code></pre>
<p>Previously for validating comparisons of dates, we needed to write
<a href="https://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations">custom validators</a>
or use a gem like <a href="https://github.com/codegram/date_validator">date_validator</a>.</p>
<p>However,
<a href="https://github.com/rails/rails/pull/40095">Rails 7 has added ComparisonValidator</a>
which provides a way to easily validate comparisons with another value, proc, or
attribute. Let's assume we have a model <code>Blog</code> with an <code>end_date</code> attribute.</p>
<h3>Before</h3>
<p>If we want to validate the <code>end_date</code> attribute for the provided value or then
we would need to write a
<a href="https://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations">custom validator</a>
or use a gem like <a href="https://github.com/codegram/date_validator">date_validator</a>.</p>
<pre><code class="language-ruby"># Using date_validator gem
class Blog &lt; ApplicationRecord
  # validate against provided value
  validates :end_date, date: { after: Proc.new { Date.today } }
  # validate against another attribute
  validates :end_date, date: { after: :start_date }
end
</code></pre>
<h3>Rails 7 onwards</h3>
<p>We can use <a href="https://github.com/rails/rails/pull/40095">ComparisonValidator</a> to
validate the comparison of the <code>end_date</code> attribute for a provided value.</p>
<pre><code class="language-ruby">class Blog &lt; ApplicationRecord
  # validate against provided value
  validates_comparison_of :end_date, greater_than: -&gt; { Date.today }
  # validate against another attribute
  validates :end_date, greater_than: :start_date
end
</code></pre>
<p><a href="https://github.com/rails/rails/pull/40095">ComparisonValidator</a> also provides
helpers like <code>greater_than</code>, <code>greater_than_or_equal_to</code>, <code>equal_to</code>,
<code>less_than</code>, <code>less_than_or_equal_to</code> and <code>other_than</code>.</p>
<p>Check out this <a href="https://github.com/rails/rails/pull/40095">pull request</a> for
more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds ActiveRecord::Relation#structurally_compatible?]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-active-record-relation-structurally-compatible"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-active-record-relation-structurally-compatible.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-active-record-relation-structurally-compatible</id>
      <published>2021-09-15T00:00:00.000Z</published>
      <updated>2021-09-15T00:00:00.000Z</updated>
      <author>
        <name>Gaurav Varma</name>
        <uri>https://www.bigbinary.com/blog/authors/gaurav-varma</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-active-record-relation-structurally-compatible.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.0 adds ActiveRecord::Relation#structurally_compatible?]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-active-record-relation-structurally-compatible"><![CDATA[<p><a href="https://guides.rubyonrails.org/active_record_querying.html">ActiveRecord</a> is
one of the most powerful features in Rails. With <code>ActiveRecord</code> we can easily
query and handle database objects without writing any SQL.</p>
<p>By using <code>ActiveRecord Query Interface</code>, we can perform various query operations
like <code>Joins</code>, <code>Group</code>, <code>Find</code>, <code>Order</code>. We can also chain relations with
<code>where</code>, <code>and</code>, <code>or</code>, <code>not</code> but for <code>and</code> or <code>or</code> the two chaining relations
must be structurally compatible.</p>
<p>For any two relations to be
<a href="https://github.com/rails/rails/blob/c577657f6de64b743b12a21108dc9cc5cfc35098/activerecord/lib/active_record/relation/query_methods.rb#L650">Structurally Compatible</a>
they must be scoping the same model, and they must differ only by the <code>where</code>
clause when no <code>group</code> clause has been defined. If a <code>group</code> clause is present,
then the relations must differ by the <code>having</code> clause. Also, neither relation
may use a <code>limit</code>, <code>offset</code>, or <code>distinct</code> method.</p>
<p>Previously for <code>and</code> or <code>or</code> query methods, we needed to make sure that the two
relations are structurally compatible otherwise, <code>ActiveRecord</code> would raise an
error.</p>
<p>However,
<a href="https://github.com/rails/rails/pull/41841">Rails 7 has added ActiveRecord::Relation#structurally_compatible?</a>
which provides a method to easily tell if two relations are structurally
compatible. We can use this method before we run <code>and</code> or <code>or</code> query methods on
any two relations.</p>
<p>Let's assume we have two models, <code>Blog</code> and <code>Post</code>, with the following relations</p>
<pre><code class="language-ruby"># app/models/blog.rb
class Blog &lt; ApplicationRecord
  has_many :posts
end
</code></pre>
<pre><code class="language-ruby"># app/models/post.rb
class Post &lt; ApplicationRecord
  belongs_to :blog
end
</code></pre>
<h3>Before</h3>
<p>If we run <code>or</code> query between incompatible relations, we would get an
ArgumentError.</p>
<pre><code class="language-ruby">relation_1 = Blog.where(name: 'bigbinary blog')
relation_2 = Blog.joins(:posts).where(posts: { user_id: current_user.id})

begin
  relation_1.or(relation_2)
rescue ArgumentError
  # Rescue ArgumentError
end
</code></pre>
<h3>Rails 7 onwards</h3>
<p>We can check the structural compatibility of the two relations.</p>
<pre><code class="language-ruby">relation_1 = Blog.where(name: 'bigbinary blog')
relation_2 = Blog.where(user_id: current_user.id)

if relation_1.structurally_compatible?(relation_2) # returns true
  relation_1.or(relation_2)
end
</code></pre>
<p>Check out this <a href="https://github.com/rails/rails/pull/41841/files">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 deprecates Enumerable#sum and Array#sum]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-deprecates-enumerable-sum-and-array-sum"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-deprecates-enumerable-sum-and-array-sum.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-deprecates-enumerable-sum-and-array-sum</id>
      <published>2021-06-22T00:00:00.000Z</published>
      <updated>2021-06-22T00:00:00.000Z</updated>
      <author>
        <name>Aashish Saini</name>
        <uri>https://www.bigbinary.com/blog/authors/aashishsaini</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-deprecates-enumerable-sum-and-array-sum.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7 deprecates Enumerable#sum to the calls with non-numeric arguments. To ignore the warning we should use a suitable initial argument. Before Rails 7 After Rails 7 To avoid the deprecation...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-deprecates-enumerable-sum-and-array-sum"><![CDATA[<p>Rails 7 deprecates Enumerable#sum to the calls with non-numeric arguments. To
ignore the warning we should use a suitable initial argument.</p>
<p>Before Rails 7</p>
<pre><code class="language-ruby">=&gt; %w[foo bar].sum
=&gt; &quot;foobar&quot;

=&gt; [[1, 2], [3, 4, 5]].sum
=&gt; [1, 2, 3, 4, 5]
</code></pre>
<p>After Rails 7</p>
<pre><code class="language-ruby">=&gt; %w[foo bar].sum
=&gt; Rails 7.0 has deprecated Enumerable.sum in favor of Ruby's native implementation available since 2.4.
   Sum of non-numeric elements requires an initial argument.

=&gt; [[1, 2], [3, 4, 5]].sum
=&gt; Rails 7.0 has deprecated Enumerable.sum in favor of Ruby's native implementation available since 2.4.
   Sum of non-numeric elements requires an initial argument.
</code></pre>
<p>To avoid the deprecation warning, we should use suitable argument as below.</p>
<pre><code class="language-ruby">=&gt; %w[foo bar].sum('')
=&gt; &quot;foobar&quot;

=&gt; [[1, 2], [3, 4, 5]].sum([])
=&gt; [1, 2, 3, 4, 5]
</code></pre>
<p>Check out this <a href="https://github.com/rails/rails/pull/42080">pull request</a> for
more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds method calls for nested secrets]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-method-calls-for-nested-secrets"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-method-calls-for-nested-secrets.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-method-calls-for-nested-secrets</id>
      <published>2021-06-09T00:00:00.000Z</published>
      <updated>2021-06-09T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-method-calls-for-nested-secrets.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.0 adds method calls for nested secrets]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-method-calls-for-nested-secrets"><![CDATA[<p>Rails stores secrets in <code>config/credentials.yml.enc</code>, which is encrypted and
cannot be edited directly. You can read more about credentials management here:
<a href="https://guides.rubyonrails.org/security.html#custom-credentials">Rails security guide</a>.</p>
<p>Rails 7 allows access to nested encrypted secrets (credentials) by method calls.
We can easily access the nested secrets present in the credentials YAML file
like we've accessed top-level secrets previously:</p>
<pre><code class="language-YAML"># config/credentials.yml.enc

secret_key_base: &quot;47327396e32dc8ac825760bb31f079225c5c0&quot;
aws:
  access_key_id: &quot;A6AMOGVNQKCWLNQ&quot;
  secret_access_key: &quot;jfm6b9530tPu/h8v93W4TkUJN+b/ZMKkG&quot;
</code></pre>
<pre><code class="language-ruby">=&gt; Rails.application.credentials.aws
=&gt; {:access_key_id=&gt;&quot;A6AMOGVNQKCWLNQ&quot;, :secret_access_key=&gt;&quot;jfm6b9530tPu/h8v93W4TkUJN+b/ZMKkG&quot;}
</code></pre>
<p>Before Rails 7</p>
<pre><code class="language-ruby">=&gt; Rails.application.credentials.aws[:access_key_id]
=&gt; &quot;A6AMOGVNQKCWLNQ&quot;

=&gt; Rails.application.credentials.aws.access_key_id
=&gt; NoMethodError (undefined method `access_key_id' for #&lt;Hash:0x00007fb1adb0cca8&gt;)
</code></pre>
<p>After Rails 7</p>
<pre><code class="language-ruby">=&gt; Rails.application.credentials.aws.access_key_id
=&gt; &quot;A6AMOGVNQKCWLNQ&quot;
</code></pre>
<p>Check out this <a href="https://github.com/rails/rails/pull/42106">pull request</a> for
more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7.0 adds encryption to Active Record models]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-encryption-to-active-record"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-encryption-to-active-record.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-encryption-to-active-record</id>
      <published>2021-05-04T00:00:00.000Z</published>
      <updated>2021-05-04T00:00:00.000Z</updated>
      <author>
        <name>Akhil Gautam</name>
        <uri>https://www.bigbinary.com/blog/authors/akhilgautam</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-encryption-to-active-record.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Before Rails 7.0, to add encryption on attributes of ActiveRecord models, we had to use third-party gems like lockbox which served the purpose but at the cost of an additional dependency. Before we...]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-encryption-to-active-record"><![CDATA[<p>Before Rails 7.0, to add encryption on attributes of ActiveRecord models, we had
to use third-party gems like <a href="https://github.com/ankane/lockbox">lockbox</a> which
served the purpose but at the cost of an additional dependency.</p>
<p>Before we delve deeper, let's take a look at some terms related to
encryption:</p>
<ol>
<li><strong>Encrypt:</strong> to scramble a message in a way that
only the intended person can extract the original message.</li>
<li><strong>Decrypt:</strong> to extract the original message from an
encrypted one.</li>
<li><strong>Key:</strong> a string of characters used to encrypt/decrypt a message.</li>
<li><strong>Cipher:</strong> an algorithm used to encrypt and decrypt a message;
RSA, Blowfish, and AES are some well-known examples.</li>
<li><strong>Deterministic:</strong> a process with guaranteed results;
the sum of a set of numbers never changes.</li>
<li><strong>Non-deterministic:</strong> a process with unpredictable results;
a roll of the dice can never be predicted.</li>
</ol>
<h3>Rails 7.0</h3>
<p>Rails 7.0 adds encryption to attributes at the model level. By default, it
supports encrypting serialized attribute types using the non-deterministic
<code>AES-GCM</code> cipher.</p>
<p>To use this feature, we have to set the <code>key_derivation_salt</code>, <code>primary_key</code>, and
<code>deterministic_key</code> variables in our environment file. These <code>keys</code> can be generated by
running <code>bin/rails db:encryption:init</code>.</p>
<p>Let's enable encryption on the <code>passport_number</code> attribute of the <code>User</code>
model.</p>
<pre><code class="language-ruby"># app/models/user.rb
class User &lt; ApplicationRecord
  encrypts :passport_number
end
</code></pre>
<p>In the above code, we have asked Rails to encrypt the <code>passport_number</code>
attribute of <code>User</code> model when writing it to the database. Now, whenever we create a
<code>User</code>, we will see the encrypted value of <code>passport_number</code> in the table,
and the unencrypted value when we query using ActiveRecord.</p>
<pre><code class="language-ruby"># rails console
&gt;&gt; User.create name: &quot;Akhil&quot;, passport_number: &quot;BKLPG564&quot;
  TRANSACTION (0.1ms)  begin transaction
  User Create (0.6ms)  INSERT INTO &quot;users&quot; (&quot;name&quot;, &quot;passport_number&quot;, &quot;created_at&quot;, &quot;updated_at&quot;) VALUES (?, ?, ?, ?)  [[&quot;name&quot;, &quot;Akhil&quot;], [&quot;passport_number&quot;, &quot;{\&quot;p\&quot;:\&quot;iOUC3ESsyxY=\&quot;,\&quot;h\&quot;:{\&quot;iv\&quot;:\&quot;lDdCxI3LeoPv0hxZ\&quot;,\&quot;at\&quot;:\&quot;D50hElso0YvI6d8Li+l+lw==\&quot;}}&quot;], [&quot;created_at&quot;, &quot;2021-04-15 10:27:50.800729&quot;], [&quot;updated_at&quot;, &quot;2021-04-15 10:27:50.800729&quot;]]
  TRANSACTION (1.5ms)  commit transaction

&gt;&gt; User.last
=&gt; #&lt;User id: 1, name: &quot;Akhil&quot;, adhar: &quot;BKLPG564&quot;, created_at: &quot;2021-04-15 10:27:50.800729000 +0000&quot;, updated_at: &quot;2021-04-15 10:27:50.800729000 +0000&quot;&gt;
</code></pre>
<p>Under the hood, Rails 7 uses the
<a href="https://github.com/rails/rails/blob/9a263e9a0ffb82faa6d3153fd1f35b814a366cd5/activerecord/lib/active_record/encryption/encryptable_record.rb#L7">EncryptableRecord</a>
concern to perform encryption and decryption when saving and retrieving values
from the database.</p>
<p>Check out the <a href="https://github.com/rails/rails/pull/41659">pull request</a> for more
details of this encryption system. It is also documented in the
<a href="https://edgeguides.rubyonrails.org/active_record_encryption.html">Ruby on Rails guides</a>.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds Enumerable#sole]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-enumerable-sole"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-enumerable-sole.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-enumerable-sole</id>
      <published>2021-04-27T00:00:00.000Z</published>
      <updated>2021-04-27T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-enumerable-sole.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.0 adds Enumerable#sole]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-enumerable-sole"><![CDATA[<p>Rails 7 introduces the <code>Enumerable#sole</code> method, which can be used to find and
assert the presence of exactly one element in the enumerable.</p>
<p>The <code>Enumerable#sole</code> method is an add-on for
<a href="https://edgeapi.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-sole">ActiveRecord::FinderMethods#sole</a>
and
<a href="https://edgeapi.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find_sole_by">#find_sole_by</a>
methods, which were recently added in Rails 6.1. Please check
our blog (Link is not available)
for more details on it.</p>
<pre><code class="language-ruby">=&gt; list = [&quot;Sole Element&quot;]
=&gt; list.sole
=&gt; &quot;Sole Element&quot;

=&gt; hash = { foo: &quot;bar&quot; }
=&gt; hash.sole
=&gt; [:foo, &quot;bar&quot;]
</code></pre>
<p>The <code>Enumerable#sole</code> method raises <code>Enumerable::SoleItemExpectedError</code> error if
the enumerable is empty or contains multiple elements. When the sole element is
<code>nil</code>, it will be returned as result.</p>
<pre><code class="language-ruby">=&gt; list = [nil]
=&gt; list.sole
=&gt; nil

=&gt; list = []
=&gt; list.sole
=&gt; `Enumerable::SoleItemExpectedError (no item found)`

=&gt; list = [&quot;Apple&quot;, &quot;Orange&quot;]
=&gt; list.sole
=&gt; `Enumerable::SoleItemExpectedError (multiple items found)`
</code></pre>
<p>Check out this <a href="https://github.com/rails/rails/pull/40914">pull request</a> for
more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds build/create constructors to has_one :through]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-allows-build-and-create-association-constructors-on-has-one-through"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-allows-build-and-create-association-constructors-on-has-one-through.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-allows-build-and-create-association-constructors-on-has-one-through</id>
      <published>2021-04-06T00:00:00.000Z</published>
      <updated>2021-04-06T00:00:00.000Z</updated>
      <author>
        <name>Akanksha Jain</name>
        <uri>https://www.bigbinary.com/blog/authors/akankshajain</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-allows-build-and-create-association-constructors-on-has-one-through.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7 allows constructors (build_association and create_association) on has_one :through associations]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-allows-build-and-create-association-constructors-on-has-one-through"><![CDATA[<br/>
<h3>What are <code>build_association</code> and <code>create_association</code> constructors?</h3>
<p>When we declare either a <code>belongs_to</code> or <code>has_one</code> association,
the declaring class automatically gains the following methods
related to the association:</p>
<ol>
<li>build_association(attributes = {})</li>
<li>create_association(attributes = {})</li>
</ol>
<p>In the above methods
_<code>association</code> is replaced with the symbol(association name)
passed as the first argument while declaring the associations.
For example:</p>
<pre><code class="language-ruby">class Book &lt; ApplicationRecord
  belongs_to :author
end

@book.build_author(name: 'John Doe', email: 'john_doe@example.com')
#=&gt; Returns a new Author object, instantiated with the passed attributes
#=&gt; Links through the book's object foreign key
#=&gt; New author object won't be saved in the database

@book.create_author(name: 'John Doe', email: 'john_doe@example.com')
#=&gt; Returns a new Author object, instantiated with the passed attributes
#=&gt; Links through the book's object foreign key
#=&gt; The new author object will be saved in the database after passing all of the validations specified on the Author model
</code></pre>
<h3>Before Rails 7</h3>
<p>The <code>build_association</code> and <code>create_association</code> constructors
were only supported by
<code>belongs_to</code> and <code>has_one</code> associations.</p>
<p>Consider the example below.
We have a model, <strong>Member</strong>,
that has a <code>has_one</code> association
with the <strong>CurrentMembership</strong> model.
It also has a <code>has_one :through</code> association
with the <strong>Club</strong> model.</p>
<pre><code class="language-ruby">class Member &lt; ApplicationRecord
  has_one :current_membership
  has_one :club, through: :current_membership
end

@member.build_club
#=&gt; NoMethodError (undefined method `build_club' for #&lt;Member:0x00007f9ea2ebd3e8&gt;)
#=&gt; Did you mean?  build_current_membership

@member.create_club
#=&gt; NoMethodError (undefined method `create_club' for #&lt;Member:0x00007f9ea2ebd3e8&gt;)
#=&gt; Did you mean?  create_current_membership
</code></pre>
<h3>After Rails 7</h3>
<p>Users are allowed to use constructors
(<code>build_association</code> and <code>create_association</code>)
on <code>has_one :through</code> associations
along with <code>belongs_to</code> and <code>has_one</code> associations.</p>
<pre><code class="language-ruby">class Member &lt; ApplicationRecord
  has_one :current_membership
  has_one :club, through: :current_membership
end

@member.build_club
#=&gt; #&lt;Club:0x00007f9ea01a8ce0&gt;

@member.create_club
#=&gt; #&lt;Club:0x00007f9ea01a8ce0&gt;
</code></pre>
<p>Check out this
<a href="https://github.com/rails/rails/pull/40007">pull request</a>
for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds Enumerable#in_order_of]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-enumerable-in-order-of"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-enumerable-in-order-of.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-enumerable-in-order-of</id>
      <published>2021-03-23T00:00:00.000Z</published>
      <updated>2021-03-23T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-enumerable-in-order-of.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.0 adds Enumerable#in_order_of]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-enumerable-in-order-of"><![CDATA[<p>Rails 7 introduces the <code>Enumerable#in_order_of</code> method, by which we can order
and constrain any enumerable collection using a key-series pair.</p>
<pre><code class="language-ruby">=&gt; Item = Struct.new(:price)
=&gt; items = [Item.new(24), Item.new(32), Item.new(16)]

=&gt; items.in_order_of(:price, [16, 32, 24])
=&gt; [#&lt;struct Item price=16&gt;, #&lt;struct Item price=32&gt;, #&lt;struct Item price=24&gt;]
</code></pre>
<p>If any value in the series has no associated records in the enumerable
collection, it will be ignored and the rest will be returned in the result.</p>
<pre><code class="language-ruby">=&gt; items.in_order_of(:price, (15..25))
=&gt; [#&lt;struct Item price=16&gt;, #&lt;struct Item price=24&gt;]
</code></pre>
<p>Similarly, any values not included in the series will be omitted from the final
result.</p>
<pre><code class="language-ruby">=&gt; items.in_order_of(:price, [16, 32])
=&gt; [#&lt;struct Item price=16&gt;, #&lt;struct Item price=32&gt;]
</code></pre>
<p>Check out this <a href="https://github.com/rails/rails/pull/41333">pull request</a> for
more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds ActiveRecord::Relation#excluding]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-activerecord-relation-excluding"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-activerecord-relation-excluding.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-activerecord-relation-excluding</id>
      <published>2021-03-16T00:00:00.000Z</published>
      <updated>2021-03-16T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-activerecord-relation-excluding.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.0 adds ActiveRecord::Relation#excluding]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-activerecord-relation-excluding"><![CDATA[<p>We might have used
<a href="https://www.rubydoc.info/docs/rails/Array:excluding">Array#excluding</a> method to
return an array after eliminating specific elements which are passed as an
argument.</p>
<pre><code class="language-ruby">=&gt; [&quot;John&quot;, &quot;Sam&quot;, &quot;Oliver&quot;].excluding(&quot;Sam&quot;)
=&gt; [&quot;John&quot;, &quot;Oliver&quot;]
</code></pre>
<p>When it comes to active record queries, we usually make use of
<a href="https://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions">NOT condition</a>
query to eliminate specific records from the result.</p>
<pre><code class="language-ruby">=&gt; users = User.where.not(id: current_user.id)
=&gt; &quot;SELECT \&quot;users\&quot;.* FROM \&quot;users\&quot; WHERE \&quot;users\&quot;.\&quot;id\&quot; != 1&quot;
</code></pre>
<p>This is simplified with Rails 7's newly-introduced
<code>ActiveRecord::Relation#excluding</code> method.</p>
<pre><code class="language-ruby">=&gt; users = User.excluding(current_user)
=&gt; &quot;SELECT \&quot;users\&quot;.* FROM \&quot;users\&quot; WHERE \&quot;users\&quot;.\&quot;id\&quot; != 1&quot;

# We can also pass a collection of records as an argument

=&gt; comments = Comment.excluding(current_user.comments)
=&gt; &quot;SELECT \&quot;comments\&quot;.* FROM \&quot;comments\&quot; WHERE \&quot;comments\&quot;.\&quot;id\&quot; NOT IN (1, 2)&quot;
</code></pre>
<p>The excluding method applies to activerecord association as well.</p>
<pre><code class="language-ruby">=&gt; comments = current_user.comments.excluding(comment1, comment2)
=&gt; &quot;SELECT \&quot;comments\&quot;.* FROM \&quot;comments\&quot; WHERE \&quot;comments\&quot;.\&quot;user_id\&quot; = 1 AND \&quot;comments\&quot;.\&quot;id\&quot; NOT IN (1, 2)&quot;
</code></pre>
<p>The alias method <code>without</code> can also be used instead of <code>excluding</code>.</p>
<pre><code class="language-ruby">=&gt; users = User.without(current_user)
=&gt; &quot;SELECT \&quot;users\&quot;.* FROM \&quot;users\&quot; WHERE \&quot;users\&quot;.\&quot;id\&quot; != 1&quot;

=&gt; comments = Comment.without(comment1)
=&gt; &quot;SELECT \&quot;comments\&quot;.* FROM \&quot;comments\&quot; WHERE \&quot;comments\&quot;.\&quot;id\&quot; != 1&quot;
</code></pre>
<p>Check out these pull request <a href="https://github.com/rails/rails/pull/41439">41439</a>
&amp; <a href="https://github.com/rails/rails/pull/41465">41465</a> for more details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds sole and find_sole_by finder methods]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-active-record-finder-methods"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-active-record-finder-methods.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-active-record-finder-methods</id>
      <published>2021-03-02T00:00:00.000Z</published>
      <updated>2021-03-02T00:00:00.000Z</updated>
      <author>
        <name>Akanksha Jain</name>
        <uri>https://www.bigbinary.com/blog/authors/akankshajain</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-active-record-finder-methods.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.0 adds ActiveRecord::FinderMethods `#sole` and `#find_sole_by`]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-active-record-finder-methods"><![CDATA[<br/>
<h3>Before Rails 7.0</h3>
<p>There were no methods defined to find and assert the presence of exactly one
record at the same time.</p>
<p>For example, we have a class Product with a <code>price</code> field and we want to find a
single product that has a price of 100. For zero or multiple products with the
price of 100, we want to raise an error. We can not add database constraints to
make a unique field of <code>price</code>.</p>
<p>Now to solve the above query, we don't have any method defined in
<code>ActiveRecord::FinderMethods</code> module. We can find a product with the given price
or raise an error if no record is found using the queries mentioned in the below
example.</p>
<pre><code class="language-ruby">Product.find_by!(price: price)
#=&gt; ActiveRecord::RecordNotFound Exception     (if no Product with the given price)
#=&gt; #&lt;Product ...&gt;                             (first product with the given price)

Product.where(price: price).first!
#=&gt; ActiveRecord::RecordNotFound Exception     (if no Product with the given price)
#=&gt; #&lt;Product ...&gt;                             (first product with the given price)
</code></pre>
<p>We can only use database constraints to make a field unique and if adding
constraints is impractical then we would have to define our own method.</p>
<p>For example:</p>
<pre><code class="language-ruby">def self.find_first!(arg, *args)
  products = where(arg, *args)

  case
  when products.empty?
    raise_record_not_found_exception!
  when products.count &gt; 0
    raise 'More than one record present'
  else
    products.first
  end
end

Product.find_first!(price: price)
#=&gt; ActiveRecord::RecordNotFound Exception     (if no Product with the given price)
#=&gt; #&lt;Product ...&gt;                             (if one Product with the given price)
#=&gt; ActiveRecord::SoleRecordExceeded Exception (if more than one Product with the given price)
</code></pre>
<h3>After Rails 7.0</h3>
<p>Rails 7.0 has added <code>#sole</code> and <code>#find_sole_by</code> methods in the
ActiveRecord::FinderMethods module. These methods are used to find and assert
the presence of exactly one record.</p>
<p>When a user wants to find a single row, but also wants to assert that there
aren't any other rows matching the condition (especially for when the database
constraints aren't enough or are impractical), then these methods come into use.</p>
<p>For example:</p>
<pre><code class="language-ruby">class Product
    validates :price, presence: true
end

Product.where([&quot;price = %?&quot;, price]).sole
#=&gt; ActiveRecord::RecordNotFound Exception     (if no Product with the given price)
#=&gt; #&lt;Product ...&gt;                             (if one Product with the given price)
#=&gt; ActiveRecord::SoleRecordExceeded Exception (if more than one Product with the given price)

Product.find_sole_by(price: price)
#=&gt; ActiveRecord::RecordNotFound Exception     (if no Product with the given price)
#=&gt; #&lt;Product ...&gt;                             (if one Product with the given price)
#=&gt; ActiveRecord::SoleRecordExceeded Exception (if more than one Product with the given price)
</code></pre>
<p>Check out the <a href="https://github.com/rails/rails/pull/40768">pull request</a> for more
details.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Rails 7 adds Enumerable#maximum]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/rails-7-adds-enumerable-maximum"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-enumerable-maximum.png"/>
      <id>https://www.bigbinary.com/blog/rails-7-adds-enumerable-maximum</id>
      <published>2021-02-23T00:00:00.000Z</published>
      <updated>2021-02-23T00:00:00.000Z</updated>
      <author>
        <name>Ashik Salman</name>
        <uri>https://www.bigbinary.com/blog/authors/ashiksp</uri>
      </author>
      <category term="Rails"/>
      <category term="Rails 7"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/rails-7-adds-enumerable-maximum.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Rails 7.0 adds Enumerable#maximum]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/rails-7-adds-enumerable-maximum"><![CDATA[<p>Rails 7 adds support for <code>Enumerable#maximum</code> and <code>Enumerable#minimum</code> to easily
calculate the maximum and minimum value from a collection of enumerable
elements.</p>
<p>Before Rails 7, we could only achieve the same results with a combination of
<code>map</code> &amp; <code>max</code> or <code>min</code> functions over the enumerable collection.</p>
<pre><code class="language-ruby">=&gt; Item = Struct.new(:price)
=&gt; items = [Item.new(12), Item.new(8), Item.new(24)]

=&gt; items.map { |x| x.price }.max
=&gt; 24

=&gt; items.map { |x| x.price }.min
=&gt; 8
</code></pre>
<p>This is simplified with Rails 7's newly-introduced <code>maximum</code> and <code>minimum</code>
methods.</p>
<pre><code class="language-ruby">=&gt; items.maximum(:price)
=&gt; 24

=&gt; items.minimum(:price)
=&gt; 8
</code></pre>
<p>These methods are available through Action Controller's
<a href="https://api.rubyonrails.org/v6.1.0/classes/ActionController/ConditionalGet.html#method-i-fresh_when">fresh_when</a>
and
<a href="https://api.rubyonrails.org/v6.1.0/classes/ActionController/ConditionalGet.html#method-i-stale-3F">stale?</a>
for convenience.</p>
<pre><code class="language-ruby"># Before Rails 7

def index
  @items = Item.limit(20).to_a
  fresh_when @items, last_modified: @items.pluck(:updated_at).max
end

# After Rails 7

def index
  @items = Item.limit(20).to_a
  fresh_when(@items)
end
</code></pre>
<p>The <code>etag</code> or <code>last_modified</code> header values will be properly set here based on
the maximum value of the <code>updated_at</code> field.</p>
<p>Check out this <a href="https://github.com/rails/rails/pull/41404">pull request</a> for
more details.</p>
]]></content>
    </entry>
</feed>