前提
- オブジェクトの配列をビューで表示したい
- objectはActiveRecordとは関係ない
- オブジェクトには一意の値が振られていない
render
をeachで回すとレンダリングが遅い
|
|
= "#{index}番目のrecord"
Rendering records/index.html.slim within layouts/application
Rendered records/_record.html.slim (7.8ms)
Rendered records/_record.html.slim (0.2ms)
Rendered records/_record.html.slim (0.7ms)
Rendered records/_record.html.slim (0.2ms)
Rendered records/_record.html.slim (0.3ms)
Rendered records/_record.html.slim (0.8ms)
Rendered records/_record.html.slim (0.3ms)
Rendered records/_record.html.slim (0.2ms)
Rendered records/_record.html.slim (0.3ms)
Rendered records/_record.html.slim (0.4ms)
Rendered records/_record.html.slim (0.7ms)
Rendered records/_record.html.slim (0.3ms)
Rendered records/_record.html.slim (0.2ms)
Rendered records/_record.html.slim (0.2ms)
Rendered records/_record.html.slim (0.2ms)
Rendered records/_record.html.slim (0.3ms)
Rendered records/index.html.slim within layouts/application (40.8ms)
Completed 200 OK in 1373ms (Views: 53.3ms | ActiveRecord: 0.0ms)
indexの代わりにrecord_counter
を用いる
|
|
= "#{record_counter}番目のrecord"
このように、hoge_counter
というメソッドで、それぞれ一意のindexが取得できる。
Rendering records/index.html.slim within layouts/application
Rendered collection of records/_record.html.slim [16 times] (132.2ms)
Rendered records/index.html.slim within layouts/application (147.1ms)
Completed 200 OK in 1025ms (Views: 176.6ms | ActiveRecord: 0.0ms)
Railsには便利なメソッドが用意されているもんだ。