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@postscollection.So, in a sense you are trying to do
<%= post.posts.comments %>.Here’s how the code should look: