LoginSignup
60
49

More than 5 years have passed since last update.

partialではインスタンス変数を参照しない方がいい

Posted at

なぜ?

partialは呼び出し元のテンプレートとだけ紐づけておくようにしたほうがいい。

インスタンス変数を使うと、コントローラとも結びついてしまい、結果としてpartialとして切り出したのに再利用性が低くなる。

index.html.erb
<%= render partial: 'shared/form' %>
_form.html.erb
# これはよくない
<%= form_for @item %>

具体的には、

  • controller側でインスタンス変数の名前や挙動を変更したとき、partial側も変更しなければならなくなる。
  • 特定のモデルのデータと関連づけられてしまうので、フレキシブルに使うことができない。

対処法

代わりに locals を使うとよい。

index.html.erb
# locals を使う
<%= render partial: 'shared/form', locals: item: @item %> 

_form.html.erb
# こっちがよい
<%= form_for item %>

localsを使うことで、partial内ではインスタンス変数ではなく、ローカル変数として扱える。


初心者のときに書いたコードでpartialにインスタンス変数を使っていた。

後になってcontrollerを修正するときに、案の定どのcontrollerと結びついているのがわからなくなり、自分が書いたコードなのにハマった。

参考

https://qiita.com/hmuronaka/items/daf2904e3f703448f506
https://code.i-harness.com/en/q/26349e

ちなみに、 partial:を省略して書くときは locals:も省略しないといけない。

index.html.erb
# locals を使う
<%= render 'shared/form', item: @item %> 

60
49
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
60
49