---
title: "Rails 6 adds ActiveModel::Errors#slice!"
description: "Rails 6 adds ActiveModel::Errors#slice!"
canonical_url: "https://www.bigbinary.com/blog/rails-6-adds-activemodel-errors-slice"
markdown_url: "https://www.bigbinary.com/blog/rails-6-adds-activemodel-errors-slice.md"
---

# Rails 6 adds ActiveModel::Errors#slice!

Rails 6 adds ActiveModel::Errors#slice!

- Author: Amit Choudhary
- Published: March 26, 2019
- Categories: Rails 6, Rails

Rails 6 added [slice!](https://github.com/rails/rails/pull/34489) 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

```ruby
>> user = User.new

=> #<User id: nil, email: nil, password: nil, created_at: nil, updated_at: nil>

>> user.valid?

=> false

>> user.errors

=> #<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}]}>

>> user.errors.slice!

=> Traceback (most recent call last):
        1: from (irb):16
NoMethodError (undefined method 'slice!' for #<ActiveModel::Errors:0x00007fa1f0e46eb8>)
Did you mean?  slice_when

>> errors = user.errors.to_h
>> errors.slice!(:email)

=> {:password=>["can't be blank"]}

>> errors

=> {:email=>["can't be blank"]}
```

#### Rails 6.0.0.beta2

```ruby
>> user = User.new

=> #<User id: nil, email: nil, password: nil, created_at: nil, updated_at: nil>

>> user.valid?

=> false

>> user.errors

=> #<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}]}>

>> user.errors.slice!(:email)

=> {:password=>["can't be blank"]}

>> user.errors

=> #<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](https://github.com/rails/rails/pull/34489).

## Links

- [Human page](https://www.bigbinary.com/blog/rails-6-adds-activemodel-errors-slice)
