Edge Rails, Rails

[Edge Rails] partialのcollection時に好きな変数名をつける:Collection Partial Variable Naming

2008/07/29

# またまた遅れてごめんなさい。。。

今回の機能は、render :partial で :collection を使った場合に好きな変数名を渡せるものです。
恥ずかしながらいままで collection を知らなかったので、自分のためにもそのおさらいから。

render :partial => 'employees', :collection => @workers

Viewで render partial で外部テンプレートをよく呼び出しまが、collectionはその外部テンプレートをループさせるときに利用するものです。
上記の場合、下の _employees.html.erb が @workersの要素(workerひとりひとり)を引き取って、ぐるぐるとまわります。

1
2
名前:<%= woker.name %>
年齢:<%= worker.age %>

collectionは複数形で渡しておくと、テンプレート先で単数形で自動的に引き取るようです。これだと変数名に制約が出てくるので、今回の機能である、:asで変数名を指定することができます。

render :partial => "employees", :collection => @workers, :as => :person

上記のようにすると、workersの要素ひとつひとつがpersonとしてemployeesテンプレートで展開することができます。

今回の機能、というよりも collection を知って嬉しくなりましたが、表示は遅いようですね。。。


related posts


tags

, , ,


have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

:

:


« iPhone へアドレスブックの内容を整形してインポートする
» [Edge Rails] 入力文字数の長さを定義する : Custom Length Validation Tokenizer