Rails 6 adds ActiveModel::Errors#slice!

Amit Choudhary

By Amit Choudhary

on March 26, 2019

This blog is part of our  Rails 6 series.

Rails 6 added slice! on ActiveModel::Errors. With this addition, it becomes quite easy to select just a few keys from errors and show or return them. Before Rails 6, we needed to convert the ActiveModel::Errors object to a hash before slicing the keys.

Let's checkout how it works.

Rails 5.2

1>> user = User.new
2
3=> #<User id: nil, email: nil, password: nil, created_at: nil, updated_at: nil>
4
5>> user.valid?
6
7=> false
8
9>> user.errors
10
11=> #<ActiveModel::Errors:0x00007fc46700df10 @base=#<User id: nil, email: nil, password: nil, created_at: nil, updated_at: nil>, @messages={:email=>["can't be blank"], :password=>["can't be blank"]}, @details={:email=>[{:error=>:blank}], :password=>[{:error=>:blank}]}>
12
13>> user.errors.slice!
14
15=> Traceback (most recent call last):
16        1: from (irb):16
17NoMethodError (undefined method 'slice!' for #<ActiveModel::Errors:0x00007fa1f0e46eb8>)
18Did you mean?  slice_when
19
20>> errors = user.errors.to_h
21>> errors.slice!(:email)
22
23=> {:password=>["can't be blank"]}
24
25>> errors
26
27=> {:email=>["can't be blank"]}

Rails 6.0.0.beta2

1>> user = User.new
2
3=> #<User id: nil, email: nil, password: nil, created_at: nil, updated_at: nil>
4
5>> user.valid?
6
7=> false
8
9>> user.errors
10
11=> #<ActiveModel::Errors:0x00007fc46700df10 @base=#<User id: nil, email: nil, password: nil, created_at: nil, updated_at: nil>, @messages={:email=>["can't be blank"], :password=>["can't be blank"]}, @details={:email=>[{:error=>:blank}], :password=>[{:error=>:blank}]}>
12
13>> user.errors.slice!(:email)
14
15=> {:password=>["can't be blank"]}
16
17>> user.errors
18
19=> #<ActiveModel::Errors:0x00007fc46700df10 @base=#<User id: nil, email: nil, password: nil, created_at: nil, updated_at: nil>, @messages={:email=>["can't be blank"]}, @details={:email=>[{:error=>:blank}]}>

Here is the relevant pull request.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.