NULLを許す関連テーブルの名前をきれいに表示する
parentに紐付いたchildの名前を表示させることはよくある処理。
ただし、childが必須ではなく、かつデフォルト値がNULLの場合、
parent.child.nameでnil参照によるエラーが発生する。
こういった場合、ifをいちいちつけるのも面倒だしあまりきれいじゃない。
ヘルパーに何か突っ込んで一息で解決できないものか。
before
これだとunlessなどを使って1行で表示しようとしてもnil参照になってしまう。
<% 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 %>
だがここまで構造が似通っているのに同じ処理にまとまらないはずはない。
取得しようとする名前が違っているからいけない。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
まだまだ初歩的なところしか出来ないが、if地獄になっているところは
<%=h show_item parent.child %>
<%=h show_item parent.other_child %>
高確率でリファクタリング対象だと思うようになってきた。
地道に頑張ろう。