LoginSignup
2
0

More than 3 years have passed since last update.

Rails6 のちょい足しな新機能を試す57(Arel is_distinct_from編)

Posted at

はじめに

Rails 6 に追加されそうな新機能を試す第57段。 今回は、 Arel is_distinct_from 編です。
Rails 6 では、 Arel を使った is_distinct_fromis_not_distinct_from が追加されました。

Ruby 2.6.3, Rails 6.0.0.rc1, PostgreSQL 10.7 で確認しました。Rails 6.0.0.rc1 は gem install rails --prerelease でインストールできます。

$ rails --version
Rails 6.0.0.rc1

User モデルを作る

User モデルを作ります

$ bin/rails g model User name

User モデルを修正する

scope を使って、 is_distinct_fromis_not_distinct_from を定義します。

app/models/user.rb
class User < ApplicationRecord
  scope :is_distinct_from, ->(name) {
    users = Arel::Table.new(:users)
    where(users[:name].is_distinct_from(name))
  }

  scope :is_not_distinct_from, ->(name) {
    users = Arel::Table.new(:users)
    where(users[:name].is_not_distinct_from(name))
  }
end

seed データを作る

db/seeds.rb
User.create(name: nil)
User.create(name: 'Taro')

マイグレーションを実行し、seedデータを登録する

マイグレーションを実行します。seedデータも登録します。

$ bin/rails db:create db:migrate db:seed

rails console で確認する

rails console を実行して確認します。

is_not_distinct_from を実行してみます。

irb(main):001:0> User.is_not_distinct_from('Taro').to_a
  User Load (1.1ms)  SELECT "users".* FROM "users" WHERE "users"."name" IS NOT DISTINCT FROM 'Taro'
=> [#<User id: 2, name: "Taro", created_at: "2019-07-14 02:31:10", updated_at: "2019-07-14 02:31:10">]

is_distinct_from を実行してみます。

irb(main):002:0> User.is_distinct_from('Taro').to_a
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."name" IS DISTINCT FROM 'Taro'
=> [#<User id: 1, name: nil, created_at: "2019-07-14 02:31:10", updated_at: "2019-07-14 02:31:10">]

where.not を使って実行してみます。 is_distinct_from と違って、 検索結果が [] になることに注意してください。

irb(main):003:0> User.where.not(name: 'Taro').to_a
  User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."name" != $1  [["name", "Taro"]]
=> []

試したソース

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

参考情報

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