LoginSignup
3
2

More than 3 years have passed since last update.

Rails6 のちょい足しな新機能を試す83(excluding, including編)

Posted at

はじめに

Rails 6 に追加された新機能を試す第83段。 今回は、 excluding, including 編です。
Rails 6 には、 Array#including , Array#excluding , Enumerable#including , Enumerable#excluding が追加されました。

Ruby 2.6.4, Rails 6.0.0 で確認しました。

$ rails --version
Rails 6.0.0

今回は、name (名前) と age (年齢) 属性をもつUserモデルを作り、 including や excluding を使ったスクリプトを作って試したいと思います。

プロジェクトを作る

rails new rails_sandbox
cd rails_sandbox

User モデルを作る

name の属性をもつ User モデルを作ります。

bin/rails g model User name age:integer

seed データを作る

users と books の2つの seed データを作ります。

db/seeds.rb
User.create(
  [
    { name: 'Andy', age: 20 },
    { name: 'Bob', age: 19 },
    { name: 'Cindy', age: 18 },
    { name: 'Dave', age: 21 },
    { name: 'Ellen', age: 22 }
  ]
)

Andy, Dave, Ellen が成人 (adult) で、 Bob と Cindy が未成年 (juvenile) です。

User に scope を追加する

User モデルに scope を2つ追加します。

app/models/user.rb
class User < ApplicationRecord
  scope :adult, -> { where(age: [20..]) }
  scope :juvenile, -> { where('age < 20') }
end

スクリプトを作成する

excluding と including を使った簡単なスクリプトを作ります。

scripts/try.rb
juveniles = User.juvenile
adults = User.adult

users1 = User.all.excluding(juveniles)
p users1.map(&:name) # => ["Andy", "Dave", "Ellen"]

users2 = juveniles.including(adults)
p users2.map(&:name) # => ["Bob", "Cindy", "Andy", "Dave", "Ellen"]

# without is same as excluding
users3 = User.all.without(juveniles)
p users3.map(&:name) # => ["Andy", "Dave", "Ellen"]

rails runner を使って実行する

rails runner を使って実行すると結果は以下のようになります。

$ bin/rails runner scripts/try.rb
Running via Spring preloader in process 2019
["Andy", "Dave", "Ellen"]
["Bob", "Cindy", "Andy", "Dave", "Ellen"]
["Andy", "Dave", "Ellen"]

試したソース

試したソースは以下にあります。
https://github.com/suketa/rails_sandbox/tree/try083_excluding

参考情報

3
2
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
3
2