0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

will_save_change_to_attribute?(attr_name)でプチ・リファクタリングした例

Last updated at Posted at 2022-07-06

やりたいこと

userテーブルのemailが変更されるかどうかを判定したい、みたいなこと、あると思います。

実装!

これでもいけますが、、

!new_record? && email == email_in_database

この方がスマートですよね、と。

will_save_change_to_attribute?(:email)

何が嬉しいかというと、コードがシンプルになったのと、&&が無くなったのでRubocop様も喜んでくれました(Metrics/PerceivedComplexity)。

参考

new_record
https://railsdoc.com/page/model_new_record_q

attribute_in_database(attr_name)
https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Dirty.html#method-i-attribute_in_database

will_save_change_to_attribute?(attr_name, **options)
https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Dirty.html#method-i-will_save_change_to_attribute-3F

Class: RuboCop::Cop::Metrics::PerceivedComplexity
https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Metrics/PerceivedComplexity

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?