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 %>
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 %>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With