通过ActiveRecord的::协会:: CollectionProxy每个循环 [英] Loop through ActiveRecord::Associations::CollectionProxy with each

查看:145
本文介绍了通过ActiveRecord的::协会:: CollectionProxy每个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了活动记录4(映射遗留数据库)

I have the following models set up with active record 4 (mapping a legacy database)

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

下面的优良工程....

The following works fine....

page = Page.first
page.content.first.content_id
=> 17
page.content.second.content_id
=> 18

不过,我希望能够循环尽管像这样的所有项目

however i want to be able to loop though all the items like so

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

但它只是返回的整个集合而不是个别领域

but it simply returns the whole collection not the individual field

=> [#<PageContent content_id: 17, content_text: 'hello', content_order: 1>, #<PageContent content_id: 18, content_text: 'world', content_order: 2>] 

看来这是一个的ActiveRecord ::协会:: CollectionProxy

appears it is a ActiveRecord::Associations::CollectionProxy

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

任何人有任何想法?

anyone got any ideas?

欢呼声

推荐答案

您可能想使用地图来代替:

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

地图(又名收集)将通过一个数组和运行任何$ C $遍历c您问它在阵列,逐个的成员。它会返回一个新的数组,包含的返回值的方法调用。

map (aka collect) will iterate through an array and run whatever code you ask it to on the members of the array, one by one. It will return a new array containing the return values for those method calls.

这篇关于通过ActiveRecord的::协会:: CollectionProxy每个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆