使用each循环遍历ActiveRecord::Associations::CollectionProxy

9

我使用Active Record 4(映射旧数据库)设置了以下模型:

class Page < ActiveRecord::Base
    self.table_name = "page"
    self.primary_key = "page_id"
    has_many :content, foreign_key: 'content_page_id', class_name: 'PageContent'
end

class PageContent < ActiveRecord::Base
    self.table_name = "page_content"
    self.primary_key = "content_id"
    belongs_to :pages, foreign_key: 'page_id', class_name: 'Page'
end

以下内容正常运行....
请问还需要翻译其他的内容吗?
page = Page.first
page.content.first.content_id
=> 17
page.content.second.content_id
=> 18

然而我希望能像这样循环遍历所有项目。
page.content.each do |item|
    item.content_id
end

但是它只返回整个集合而不是单个字段。
=> [#<PageContent content_id: 17, content_text: 'hello', content_order: 1>, #<PageContent content_id: 18, content_text: 'world', content_order: 2>] 

看起来它是一个ActiveRecord::Associations::CollectionProxy

page.content.class
=> ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_PageContent

有人有什么想法吗?

谢谢。

1个回答

14

你可能希望使用map代替:

page.content.map do |item|
  item.content_id
end

map(又名collect)会遍历一个数组并逐个运行您要求的代码。它将返回一个包含这些方法调用的返回值的新数组。


1
@MSC在这种情况下不起作用,因为OP想要返回块内调用的结果。each不能做到这一点。 - Ryan Bigg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接