簡體   English   中英

迭代活動記錄結果 - ruby​​ on rails

[英]iterate through active record results - ruby on rails

我一直在努力找到這個答案,也許這太簡單了......

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

我現在如何迭代測試,以便視圖顯示來自comments和created_at字段的數據:

這是第一條評論,2012-05-09 04:21:16

這是第二條評論,2012-05-09 05:20:03

我嘗試過以下操作並收到錯誤消息。

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

@posts.each do |c|的“c” @posts.each do |c| 表示@posts集合中的特定post對象。

所以,從某種意義上說,你正試圖做<%= post.posts.comments %>

以下是代碼的外觀:

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

改變這一點:

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

我發現如果你將內部變量命名為out變量的單數,它會讓人們更容易理解 - 因此外部的@posts變成了內部的post

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM