LoginSignup
5
1

More than 3 years have passed since last update.

Rails6 のちょい足しな新機能を試す58(ActiveRecord::Errors#of_kind?編)

Posted at

はじめに

Rails 6 に追加されそうな新機能を試す第58段。 今回は、 ActiveRecord::Errors#of_kind? 編です。
Rails 6 に ActiveRecord::Errors#of_kind? メソッドが追加されました。

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 モデルを修正する

validation を追加します。

app/models/user.rb
class User < ApplicationRecord
  validates :name, presence: true
end

rails console で確認する

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

irb(main):001:0> user = User.new
=> #<User id: nil, name: nil, created_at: nil, updated_at: nil>
irb(main):002:0> user.validate
=> false
irb(main):003:0> user.errors.of_kind?(:name)
=> false
irb(main):004:0> user.errors.of_kind?(:name, :blank)
=> true
irb(main):005:0> user.errors.of_kind?(:name, "can't be blank")
=> true
irb(main):006:0> user.errors.of_kind?(:name, :presence)
=> false

試したソース

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

参考情報

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