Skip to content

Instantly share code, notes, and snippets.

@pablojimeno
Forked from zakariaf/rails7_before_after.md
Created February 22, 2022 08:21
Show Gist options
  • Select an option

  • Save pablojimeno/a85a0d3971d8c960ef79c090809e2395 to your computer and use it in GitHub Desktop.

Select an option

Save pablojimeno/a85a0d3971d8c960ef79c090809e2395 to your computer and use it in GitHub Desktop.
New Rails 7 features, Before and After

Add ComparisonValidator

Before Rails 7

class Event < ApplicationRecord
  validates :start_date, presence: true
  validates :end_date, presence: true

  validate :end_date_is_after_start_date

  private

  def end_date_is_after_start_date
    if end_date < start_date
      errors.add(:end_date, 'cannot be before the start date')
    end
  end
end

After Rails 7

class Event < ApplicationRecord
  validates :start_date, presence: true
  validates :end_date, presence: true
  
  validates_comparison_of :end_date, greater_than: :start_date
end

Disable partial_inserts as default

# == Schema Information
#
# Table name: posts
#
#  id                     :bigint
#  title                  :string
#  description            :text
#  created_at             :datetime
#  updated_at             :datetime

class Post < ApplicationRecord
end

Before

It's enabled as default

Rails.configuration.active_record.partial_inserts => true

The INSERT command does not include description as we are just passing title to the Post.new command

> Post.new(title: 'Rails 7').save

TRANSACTION (0.1ms)  begin transaction
Post Create (1.7ms)  INSERT INTO "posts" ("title", "created_at", "updated_at") VALUES (?, ?, ?)  [["title", "Rails 7"], ["created_at", "2021-12-25 20:31:01.420712"], ["updated_at", "2021-12-25 20:31:01.420712"]]
TRANSACTION (1.9ms)  commit transaction

After

It's disabled as default

Rails.configuration.active_record.partial_inserts => false

The INSERT command includes description too, even when we don't pass description to the Post.new command

> Post.new(title: 'Rails 7').save

TRANSACTION (0.1ms)  begin transaction
Post Create (1.7ms)  INSERT INTO "posts" ("title", "description", "created_at", "updated_at") VALUES (?, ?, ?)  [["title", "Rails 7"], ["description", ""], ["created_at", "2021-12-25 20:31:01.420712"], ["updated_at", "2021-12-25 20:31:01.420712"]]
TRANSACTION (1.9ms)  commit transaction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment