我使用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
有人有什么想法吗?
谢谢。
each
不能做到这一点。 - Ryan Bigg