NULLを許す関連テーブルの名前をきれいに表示する

parentに紐付いたchildの名前を表示させることはよくある処理。

ただし、childが必須ではなく、かつデフォルト値がNULLの場合、

parent.child.nameでnil参照によるエラーが発生する。

こういった場合、ifをいちいちつけるのも面倒だしあまりきれいじゃない。

ヘルパーに何か突っ込んで一息で解決できないものか。

before


<% if parent.child.nil? || parent.child_id == 0 %>
 
<% else %>
<%=h parent.child.child_name %>
<% end %>
<% if parent.other_child.nil? || parent.other_child_id == 0 %>
 
<% else %>
<%=h parent.other_child.other_child_name %>
<% end %>
これだとunlessなどを使って1行で表示しようとしてもnil参照になってしまう。


だがここまで構造が似通っているのに同じ処理にまとまらないはずはない。

取得しようとする名前が違っているからいけない。migrationで各テーブルの

名前カラムは"name"で統一してみよう。


def up
rename_column(:children, :child_name, :name)
rename_column(:other_children, :other_child_name, :name)
end
こうすればアプリケーションヘルパーにひとつヘルパーを挟むだけで

まとまるはずだ。


def show_item (obj)
obj ? obj.name : ''
end
先ほどのビューは次のようになる。

after


<%=h show_item parent.child %>
<%=h show_item parent.other_child %>
まだまだ初歩的なところしか出来ないが、if地獄になっているところは

高確率でリファクタリング対象だと思うようになってきた。

地道に頑張ろう。


  generated by feedpath Rabbit