This page looks best with JavaScript enabled
⚠️

【Rails】render内で○番目を指定する

 ·   ·  ☕ 1 分で読めます
✏️

前提

  • オブジェクトの配列をビューで表示したい
  • objectはActiveRecordとは関係ない
  • オブジェクトには一意の値が振られていない

renderをeachで回すとレンダリングが遅い

1
2
- @records.each_with_index do |record, index|
  = render 'record', record: record, index: index
= "#{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を用いる

1
= render partial: 'record', collection: @records
= "#{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には便利なメソッドが用意されているもんだ。

Share on

END
END
@aiandrox

 
目次