作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我使用事件记录 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
有人有什么想法吗?
干杯
最佳答案
您可能想改用 map
:
page.content.map do |item|
item.content_id
end
map
(又名 collect
)将遍历数组并在数组成员上逐个运行您要求的任何代码。它将返回一个新数组,其中包含这些方法调用的返回值。
关于ruby - 循环遍历 ActiveRecord::Associations::CollectionProxy 每个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18116091/
我是一名优秀的程序员,十分优秀!