ruby-on-rails – 迭代活动记录结果 – ruby​​ on rails

我一直在努力找到这个答案,也许这太简单了……

在rails中,迭代activerecord结果的最佳方法是如何拉出你想要的特定字段?

我有一个评论控制器(命名帖子),可以提取所有记录:

def index
@posts = Post.find(:all)
end

然后在索引视图中,当我使用<%= @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,comments: "here's a second comment",twitter: "please",created_at: "2012-05-09 05:20:03",updated_at: "2012-05-09 05:20:03">

我现在如何迭代测试,以便视图显示来自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 %>

解决方法

@ posts.each中的“c”执行| c |表示@posts集合中的特定post对象.

所以,从某种意义上说,你正试图做<%= post.posts.comments%>.

以下是代码的外观:

<% @posts.each do |p| %>
   <%= p.comments %>
   <%= p.created_at %>
<% end %>

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...