LoginSignup
2
0

More than 5 years have passed since last update.

ActiveRecord の where と where! (where bang) の違い

Last updated at Posted at 2018-01-31

概要

おそらく Ruby on Rails4 以降に導入されている ActiveRecord::QueryMethods#where! includes! .. などについて。

違いとは

where

where は呼び出し時に新しくオブジェクトがクローンされる。

> users = User.all
> users.where(id: 1).object_id
=> 70140175157520
> users.where(id: 1).object_id
=> 70140175100600
> users.where(id: 1).object_id
=> 70140175049660

where!

where! はクローンされない。

> users.object_id
=> 70140126836880
> users.where!(id: 1).object_id
=> 70140126836880
> users.where!(id: 1).object_id
=> 70140126836880
> users.where!(id: 1).object_id
=> 70140126836880

whereでメソッドチェーンを繰り返す使い方を考えると、こちらは元のオブジェクトのクエリをどんどん書き換えていくイメージですね。

なので、破壊的メソッドを示す ! というネーミングなのだと思います。

参考

該当のプルリクエスト。whereは内部でwhere!を利用している。
where バージョンではオブジェクトをクローンしている。

2
0
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
2
0