Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through ActiveRecord::Associations::CollectionProxy with each

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

like image 373
Pat Avatar asked Aug 08 '13 00:08

Pat


1 Answers

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.

like image 169
Ryan Bigg Avatar answered Nov 17 '22 08:11

Ryan Bigg