Boolean attributes

 

When a boolean attribute is set, then it can be only true or false. But if it is not set, then it is NULL in database or nil in Ruby. It basically means that boolean attributes can have three values. Learn when to disallow NULL values for boolean attributes and when to keep them.

Shownotes

# app/models/subscription.rb
class Subscription < ApplicationRecord
  scope :autorenew_enabled, -> { where(autorenew: true) }
  scope :autorenew_disabled, -> { where(autorenew: false) }

  def renew
    # charge customer
  end

  def deactivate
    update!(active: false)
  end
end
# lib/tasks/subscriptions.rb
namespace :subscriptions do
  desc "Renew or disable subscriptions"
  task autorenew: :environment do
    Subscription.autorenew_enabled.each(&:renew)
    Subscription.autorenew_disabled.each(&:deactivate)
  end
end
# db/migrate/20161006190530_add_not_null_to_subscriptions_autorenew.rb
class AddNotNullToSubscriptionsAutorenew < ActiveRecord::Migration[5.0]
  def change
    change_column_null :subscriptions, :autorenew, false
  end
end