Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through active record results - ruby on rails

I've been trying got find this answer, and maybe it's too simple...

In rails, how is the best way to iterate through results from activerecord pull the specific fields that you want?

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

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

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

#<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"> 

How can I now iterate through test so that the view shows the data from the comments and created_at fields:

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

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

I've tried the following and get an error.

<% @posts.each do |c| %>
   <%= c.posts.comments %>
   <%= c.posts.created_at %>
<% end %>
like image 584
user749798 Avatar asked May 10 '12 15:05

user749798


2 Answers

The "c" in @posts.each do |c| represents the specific post object in the @posts collection.

So, in a sense you are trying to do <%= post.posts.comments %>.

Here's how the code should look:

<% @posts.each do |p| %>
   <%= p.comments %>
   <%= p.created_at %>
<% end %>
like image 74
Nick Messick Avatar answered Oct 07 '22 06:10

Nick Messick


Change things to this:

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

I find it makes it easier for people to follow if you name the inner variable as the singular of the out variable -- therefore @posts on the outside becomes post on the inside.

Good luck!

like image 20
Kevin Bedell Avatar answered Oct 07 '22 05:10

Kevin Bedell