Loop through ActiveRecord::Associations::CollectionProxy with each

非 Y 不嫁゛ 提交于 2019-12-31 10:49:34

问题


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>] 

appears it is a ActiveRecord::Associations::CollectionProxy

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

anyone got any ideas?

cheers


回答1:


You probably want to use map instead:

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

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.



来源:https://stackoverflow.com/questions/18116091/loop-through-activerecordassociationscollectionproxy-with-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!