遍历活动记录结果 - ruby​​ on rails

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10537407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:22:55  来源:igfitidea点击:

iterate through active record results - ruby on rails

ruby-on-rails

提问by user749798

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?

在 Rails 中,迭代来自 activerecord 的结果的最佳方法是如何拉取您想要的特定字段?

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...

然后在索引视图中,当我使用 <%= @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"> 

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

我现在如何迭代测试,以便视图显示来自 comments 和 created_at 字段的数据:

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

这是第一条评论,2012-05-09 04:21:16

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

这是第二条评论,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 %>

回答by Nick Messick

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

中的“c”@posts.each do |c|代表@posts集合中的特定帖子对象。

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

因此,从某种意义上说,您正在尝试做<%= post.posts.comments %>.

Here's how the code should look:

以下是代码的外观:

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

回答by Kevin Bedell

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 @postson the outside becomes poston the inside.

我发现如果您将内部变量命名为 out 变量的单数,那么人们会更容易理解——因此@posts从外部变成post了内部。

Good luck!

祝你好运!