LoginSignup
25
20

More than 5 years have passed since last update.

railsのrenderの変態的な便利機能

Posted at

Railsに慣れてる人にとっては通常のことなのかもしれませんが、自分には未だに変態的だと思えるRailsのRenderの機能

複数形のモデルの配列を渡すと勝手にループ

例えば app/views/posts/show.html.erbの中でコメントの一覧を表示したい時に普通だとこう書けます。

posts/show.html.erb
<% @comments.each do |comment| %>
  <%= render 'comments/comment', comment: comment %>
<% end %>
comments/_comment.html.erb
<%= comment.name %>
<%= comment.content %>

普通ですね。

Best Practice とかいうの

これをRails風に書くと

posts/show.html.erb
<%= render @comments %>

になります。_comment.html.erbは変更しなくてOKです。変態ですね。renderさん仕事し過ぎじゃないっすか?

25
20
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
25
20