2012-05-10 43 views
5

我一直在试图找到了这个答案,也许是太简单了......迭代通过积极创纪录的业绩 - Ruby on 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, 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"> 

如何我现在可以通过测试循环,使该视图显示了意见和created_at字段中的数据:

这里的第一个评论,2012-05-09 4时21分16秒

这里的第二个意见,2012-05-09五时20分03秒

我试过以下,并得到一个错误。

<% @posts.each do |c| %> 
    <%= c.posts.comments %> 
    <%= c.posts.created_at %> 
<% end %> 
+0

那么,你得到的错误是什么? – DVG

回答

15

的 “C” 在@posts.each do |c|表示@posts集合中的特定岗位的对象。

因此,从某种意义上说,您正在尝试做<%= post.posts.comments %>

下面的代码应该是什么样子:

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

感谢您的帮助! – user749798

+0

没问题!如果可以,现在只要将答案标记为已接受。 – messick

+0

完成。谢谢! – user749798

8

改变的事情是:

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

我发现它使人们更容易,如果你的名字内变量作为单一的跟随出变量 - 因此@posts在外面变成post在里面。

祝你好运!