LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】同じscopeはmoduleに共通化しよう

Posted at

複数のクラスに共通するscopeがあるとき、moduleとして共通化する。

before

author.rb
class Author < ApplicationRecord
  scope :active, -> { where(state: 'active') }
end
book.rb
class Book < ApplicationRecord
  scope :active, -> { where(state: 'active') }
end

after

models/concerns/active_scope.rb
module ActiveScope
  extend ActiveSupport::Concern

  included do
    scope :active, -> { where(state: 'active') }
  end
end
author.rb
class Author < ApplicationRecord
  include ActiveScope
end
book.rb
class Book < ApplicationRecord
  include ActiveScope
end

RSpec

モデルと同じようにテストする

spec/models/active_scope_spec.rb
require 'rails_helper'

RSpec.describe ActiveScope, type: :model do
  describe '#active' do
    it '' do
       ...
    end
  end
end

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0