3
0

More than 1 year has passed since last update.

ignored_columns が意図せず上書きされるのを防ぐ

Last updated at Posted at 2022-09-10

ignored_columns が意図せず上書きされる可能性のあるコード

一つのモデルで既に ignored_columns をセットしていた場合に、誤って新規に ignored_columns をセットしてしまうと本来使われたくないカラムが使われてしまう不具合が引き起こされる恐れがある。

# あるモデルの10行目に ignored_columns がセットされている
self.ignored_columns = %w(foo bar)

...

# 10行目に気づかず別の行に新規で書いてしまうと10行目の ignored_columns は上書きされ、
# foo, bar のカラムが意図せず利用可能になってしまう
self.ignored_columns = %w(baz)

これを防ぐためには

以下のように変更するだけ

# before
self.ignored_columns = %w(foo bar)

# after
self.ignored_columns += %w(foo bar)

2022/10/14 追記

Rubocop Rails 2.17.0にバージョンアップ以降は Rails/IgnoredColumnsAssignment を有効化すればAuto Correct (Unsafe) 可能
https://github.com/rubocop/rubocop-rails/releases/tag/v2.17.0

Rails/IgnoredColumnsAssignment:
  Enabled: true

# or

AllCops:
  NewCops: enable

背景について

Rails本体のmainブランチに下記ドキュメント修正が入ったのを受けて。
https://github.com/rails/rails/pull/45909

また、同様のドキュメント変更がRails Style Guideに既に入っており、
https://github.com/rubocop/rails-style-guide/pull/301

Rubocop Railsにもこれを推奨するCopが追加されようしている(記事執筆時点)のを観測
https://github.com/rubocop/rubocop-rails/pull/514

2022/10/14 追記

上記#514のマージが待ち切れず私の方で巻き取って対応の続きを進めることになり、
https://github.com/rubocop/rubocop-rails/pull/514#issuecomment-1243124817

rebaseのために別でオープンしたPullRequestが無事マージされた
https://github.com/rubocop/rubocop-rails/pull/771


Changelogにはco-authorという形で載せていただくことができました :tada:
また、そのあたり配慮してくださった@koicさんに感謝です :pray:

Screen Shot 2022-10-24 at 9.43.32.png

image.png

参考リンク

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