我在 View (.html.erb) 中有以下内容:
<% @posts = GetAllPostsFunctions %> (removed for berivity)
<% @posts.each do |post| %>
<%= post.title %>
<%= render :partial => "posts/post_show" %>
<% end %>
post_show 部分具有以下内容:
....
<td><%=h @post.title %> </td>
但我收到以下错误
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.title
有任何想法吗?
最佳答案
你也可以简单地使用 :collection 来渲染 :partial。将 :collection 值中的每个项目传递给共享部分名称的局部变量。
<% @posts = GetAllPostsFunctions %> (removed for berivity)
<%= render :partial => "posts/post_show", :collection => @posts %>
在这种情况下,Rails 将为 @posts 中的每个项目呈现 post_show,并将局部变量 post_show 设置为当前项目。它还提供了方便的计数器方法。
成功使用这种方法需要将 app/views/posts/_post_show.html.erb 部分重命名为 app/views/posts/_post.html.erb 或将您的部分中每次出现的帖子更改为 post_show。如果您将部分重命名为传统的 _post.html.erb,那么您只需执行以下操作:
<%= render :partial => @posts %>
这将呈现
@posts
中每个帖子的部分内容多变的。
关于ruby-on-rails:在列表中的每个项目上渲染部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1540062/