我一直在努力找到这个答案,也许这太简单了......
在rails中,迭代activerecord结果的最佳方法是如何拉出你想要的特定字段?
我有一个评论控制器(命名帖子),可以提取所有记录:
def index
@posts = Post.find(:all)
end
Run Code Online (Sandbox Code Playgroud)
然后在索引视图中,当我使用<%= @posts%>时,我得到所有数据......这很棒...
#<Post id: 1, user_id: "9", picture: nil, comments: "here's a first comment", title: nil, twitter: nl, frame: nil, created_at: "2012-05-09 04:21:16", updated_at: "2012-05-09 04:21:16"> #<Post id: 2, user_id: "9", picture: nil, comments: "here's a second comment", title: nil, twitter: "please", frame: nil, created_at: "2012-05-09 05:20:03", updated_at: "2012-05-09 05:20:03">
Run Code Online (Sandbox Code Playgroud)
我现在如何迭代测试,以便视图显示来自comments和created_at字段的数据:
这是第一条评论,2012-05-09 04:21:16
这是第二条评论,2012-05-09 05:20:03
我尝试过以下操作并收到错误消息.
<% @posts.each do |c| %>
<%= c.posts.comments %>
<%= c.posts.created_at %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
Nic*_*ick 19
"c" @posts.each do |c|表示@posts集合中的特定post对象.
所以,从某种意义上说,你正在尝试做<%= post.posts.comments %>.
以下是代码的外观:
<% @posts.each do |p| %>
<%= p.comments %>
<%= p.created_at %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
改变这一点:
<% @posts.each do |post| %>
<%= post.comments %>
<%= post.created_at %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
我发现如果你将内部变量命名为out变量的单数,它会让人们更容易理解 - 因此@posts在外部变得post在内部.
祝好运!
| 归档时间: |
|
| 查看次数: |
22453 次 |
| 最近记录: |