ruby – 循环遍历ActiveRecord :: Associations :: CollectionPr
发布时间:2020-12-16 21:20:05 所属栏目:百科 来源:网络整理
导读:我有以下模型设置活动记录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'endclass PageContent ActiveRecord::Base
我有以下模型设置活动记录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 有人有任何想法吗? 干杯 解决方法
您可能想要使用地图:
page.content.map do |item| item.content_id end map(aka collect)将遍历一个数组,并逐个运行你要求它在数组成员上的任何代码.它将返回一个包含这些方法调用的返回值的新数组. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |