Iterate according to the results of active recording - ruby ​​on rails

I tried to find this answer, and maybe it is too simple ...

In rails, what is the best way to iterate over the results of activerecord, pull out the fields you need?

I have a controller for comments (named posts) that pull all posts:

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

Then in the index view, when I use <% = @ posts%>, I get all the data ... which is great ...

#<Post id: 1, user_id: "9", picture: nil, comments: "here 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 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"> 

How can I now iterate over the test so that the view displays data from comments and created fields:

Here is the first comment, 2012-05-09 04:21:16

Here is the second comment, 2012-05-09 05:20:03

I tried the following and get an error message.

<% @posts.each do |c| %>
   <%= c.posts.comments %>
   <%= c.posts.created_at %>
<% end %>
+5
source share
2 answers

"c" @posts.each do |c| post @posts.

, - <%= post.posts.comments %>.

:

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

:

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

, , out, @posts post .

!

+8

All Articles