---
title: 'This week in #dev (Aug 9, 2024)'
teaser: 'Renaming keys in a Hash, sanitizing input for a LIKE query, and toggling
  attributes in Rails.

  '
tags: this week in dev,rails,ruby,activerecord
author: thoughtbot
published_on: 2024-08-20
---

Welcome to another edition of [This Week in #dev](https://thoughtbot.com/blog/tags/this-week-in-dev),
a series of posts where we bring some of our most interesting Slack
conversations to the public.

## Key Renaming with `Hash#transform_keys`

[Joël Quenneville][joelq] shares that [`Hash#transform_keys`] allows you to pass a
map of old to new keys if you want to do a key rename:

```ruby
{old: 1, dont_care: 2}.transform_keys(old: :new)
#=> {new: 1, dont_care: 2}
```

[`Hash#transform_keys`]: https://docs.ruby-lang.org/en/3.3/Hash.html#method-i-transform_keys

## Sanitizing Input for a LIKE Query

[Summer ☀️][summer] mentions that Active Record has a [`sanitize_sql_like` method] for
sanitizing input for a `LIKE` query.

```ruby
sanitize_sql_like("100% true!")
# => "100\\% true!"

sanitize_sql_like("snake_cased_string")
# => "snake\\_cased\\_string"
```

[`sanitize_sql_like` method]: https://api.rubyonrails.org/v7.2/classes/ActiveRecord/Sanitization/ClassMethods.html#method-i-sanitize_sql_like

## Toggling Attributes in Rails

[Matheus Richard][matheus] learned about Active Record's [`toggle` method] that assigns
the boolean opposite of an attribute.

```ruby
user = User.first
user.banned? # => false
user.toggle(:banned)
user.banned? # => true
```

<aside class="warn">
  <p>This method toggles directly the underlying value without calling any setter.
  Use <a href="https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-toggle-21">
  <code>toggle!</code></a> if you want to use the attribute setter.
  </p>
</aside>

[`toggle` method]: https://api.rubyonrails.org/v7.2/classes/ActiveRecord/Persistence.html#method-i-toggle

## Thanks

This edition was brought to you by [Joël Quenneville][joelq], [Matheus Richard][matheus], and [Summer ☀️][summer]. Thanks to all contributors! 🎉

[joelq]: https://thoughtbot.com/blog/authors/joel-quenneville
[matheus]: https://thoughtbot.com/blog/authors/matheus-richard
[summer]: https://thoughtbot.com/blog/authors/summer
