[RAILS] It's easy to forget = render @collection, so leave a note

What is this?

It's a very rudimentary thing, but in a certain file (for convenience, ** "caller file" **)

- @comments.each do |comment|
   = render 'comment', comment: comment

Write as above, in the _comment partial

slim:_comment.html.slim


= comment.body

I think it is common to display a "comment list". At this time, the calling file

= render @comments

You can get the same result by simply writing in one line. However, there are two conditions.

--The partial ** file name is the singular form of the collection name passed ** --The partial is ** in the view directory with the same name as the collection name **

In other words, this combination is OK (the lower row is the partial name you want to call)

= render @messages
# messages/_message

= render @comments
# comments/_comment

This combination is useless. (Same as the bottom)

= render @messages
# messages/_messages (Plural form)

= render @comments
# posts/_comment (Directory is NG)

I made a note because it's easy to forget: relaxed:

Click here for the description in the Rails guide (Thank you for your advice!): Layout and Rendering --- 3.4.5 Render Collection (https://railsguides.jp/layouts_and_rendering.html#%E3%82%B3%E3%83%AC%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%82%92%E3%83%AC%E3%83%B3%E3%83%80%E3%83%AA%E3%83%B3%E3%82%B0%E3%81%99%E3%82%8B)

TIPS

For example, if you write = render @ comments, Rails will automatically look for the file in comments/_comment, so ** even if the calling file is not in the comments directory ** = render @ comments I was able to call @comment repeatedly.

So, for example, on the posts # show action page

slim:posts/show.html.slim


 = render @comments

Even if you write, comments/_comment is called automatically. It's amazing. : grinning:

Recommended Posts

It's easy to forget = render @collection, so leave a note
How to leave a comment
I passed the Java test level 2 so I will leave a note
[Java beginner] I got a little deeper understanding of "It's time to use new", so make a note
It's good to go to a programming school.
I was a little addicted to the S3 Checksum comparison, so I made a note.