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 5 years have passed since last update.

Railsのnilチェックの方針

Last updated at Posted at 2019-09-24

なんのための方針か

Railsでサービスを開発していると、nilチェックの仕方もルール化できると効率が上がるためチームとして決めると良い。
毎回どこまでチェックすべきか考えると効率が悪い。

方針

  1. 各入力がnilableかどうか考える
  2. nilableの入力は、nilのパターンでどうするか仕様を考える
    1. デフォルトの値を使う→conversion method(to_sとかto_iとか)
    2. 処理をスキップする
  3. nilableじゃない入力はnilパターンは想定しない。想定外パターンは落としたほうが発見しやすい

解説

1で入力とは、

  • 引数
  • has_many, belongs_toなどのassociation
  • カラムの値

nilableとはnilになる可能性があるかどうか

  • 引数はnilableだと考えておいたほうが良い
  • associationはhas_manyの場合はnilableではない
  • belongs_toはrails5以降はniableではない(optional: trueをつけない限り)
  • カラムの値は必須じゃないものはnilable

まとめ

nilチェックというとnilのパターンを消したくなるんだけれど、Railsの開発においてはnilは日常茶飯事なので、nilのパターンを意識するということが大事だと思います。

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?