LoginSignup
5
1

More than 3 years have passed since last update.

Rails6 のちょい足しな新機能を試す 122(enum negative warning 編)

Posted at

はじめに

Rails 6 に追加された新機能を試す第122段。 今回は、enum negative warning 編です。
Rails 6 では、 enum の要素で、 not_ で始まるものがあるとワーニングが出るようになっています。
これは、Rails 6 では、 enum を使うと not_ がつくデフォルトスコープが自動的に定義されるようになったからです。

Ruby 2.6.5, Rails 6.0.2.1, Rails 5.2.4.1 で確認しました。 (Rails 6.0.0 でこの修正が入っています。)

$ rails --version
Rails 6.0.2.1

今回は、 name と generation の属性を持つ Child モデルを作り、enum を定義してワーニングを確認します。

Rails プロジェクトを作る

Rails プロジェクトを新たに作成します。

$ rails new rails_sandbox
$ cd rails_sandbox

Child モデルを作る

namegeneration を持つ Child モデルを作ります。

$ bin/rails g model Child name generation:integer

Child モデルに enum を追加する

enum を定義します。このとき要素として、 babynot_baby を定義します。

app/models/child.rb
class Child < ApplicationRecord
  enum generation: %i[baby not_baby]
end

マイグレーションを実行する

マイグレーションを実行します。

bin/rails db:create db:migrate

rails console で確認する

rails c を実行します。

$ bin/rails c
Running via Spring preloader in process 344
Loading development environment (Rails 6.0.2.1)

Child を実行すると次のように2行のワーニングが出ます。

irb(main):001:0> Child
An enum element in Child uses the prefix 'not_'. This will cause a conflict with auto generated negative scopes.
Creating scope :not_baby. Overwriting existing method Child.not_baby.
=> Child (call 'Child.connection' to establish a connection)

Rails 5 では

Rails 5.2.4.1 では、 not_baby のスコープが定義されないので、ワーニングも出ません。

試したソース

参考情報

5
1
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
5
1