LoginSignup
8
5

More than 3 years have passed since last update.

【Rails】toggleとtoggle!の使い方

Posted at

toggleとtoggle!

toggle(:hoge)とtoggle!(:hoge)の大きな違いは「データベースにセーブされるかどうか」「戻り値」の違いになります。

toggle:インスタンスに保存されているbooleanの値を反転する(データベースには変更を反映しない)。処理成功時に指定のbooleanを反転させたインスタンス自身をreturnしてくれます。(selfを返す)

toggle!:インスタンスに保存されているbooleanの値を反転させて、データベースに保存してくれます。処理成功時にtrueをreturnしてくれます。

toggle(:hoge)でデータベースに値を保存したい場合はsaveメソッドを使えば保存できます。

使用例

以下、toggle(:activated)の使用例です。

toggle
rails c
#データベースからデータを取得。インスタンスのactivatedの値がtrueである
user = User.first
>User id: 1, name: "Example User", email: "example@railstutorial.org" activated: true
user.activate
>true

#userインスタンスのacticatedの値がfalseになる
user.toggle(:activated)
>User id: 1, name: "Example User", email: "example@railstutorial.org" activated: false


#再度データベースから代入しなおしたら、user.acticatedがtrueのまま代入される
user = User.first
>User id: 1, name: "Example User", email: "example@railstutorial.org" activated: true

以下、toggle!(:activated)の使用例です。(update_at等、一部割愛しています)

toggle!
rails c
#データベースからデータを取得。インスタンスのacticatedの値がtrueである
user = User.first
>User id: 1, name: "Example User", email: "example@railstutorial.org" activated: true
user.activate
>true

#userインスタンスのacticatedの値がfalseになる
user.toggle!(:activated)
(0.1ms)  begin transaction
  User Update (4.1ms)  UPDATE "users" SET "updated_at" = ?, "activated" = ? WHERE "users"."id" = ? ["activated", 0], ["id", 1]
   (5.7ms)  commit transaction
>User id: 1, name: "Example User", email: "example@railstutorial.org" activated: false


#再度データベースから代入しなおしたら、user.acticatedがfalseで代入される(つまり、データベースに変更が反映されている)
user = User.first
>User id: 1, name: "Example User", email: "example@railstutorial.org" activated: false

参考

Rails の toggle と toggle! の違い
https://www.eiji56.com/2017/06/toggle/

8
5
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
8
5