Rails render 如何找到变量

How Rails render finds variable

简单示例:

index.html.erb:

<% @posts.each do |post| %>
 <%= post.title %>
<% end %>

我可以重构它并将内容移动到 _post.html.erb 部分:

index.html.erb:

<%= render @posts %>

_post.html.erb:

 <%= post.title %>

那么 Rails 如何在不创建块的情况下传递每个 post 的属性? 我的 posts_controller 索引操作只定义了 @posts = Post.all

我认为可能是部分 (post) 的名称,但看起来像是另一个 Rails 约定(复数和单数命名)。是吗?

非常感谢分享!

Rails 通过查看集合中的模型名称来确定要使用的局部名称。呈现集合的完整语法如下:

<%= render partial: "post", collection: @posts %>

但是有一个shorthand:

<%= render @posts %>

根据文档:

When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is _post, and within the _post partial, you can refer to post to get the instance that is being rendered.

您可以在 rails guides

中找到详细说明