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
same trouble and still looking for an answer, it seems that it's because of rails 4 and in rails 3 that might work.
ReplyDeletehttp://olivierlacan.com/posts/associations-in-rails-4/
Now I got it, as we do not use the @target thatw why we get an: ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_PageContent or something like that, I solved using collect method to access data and print what I need, the code will be something like this:
ReplyDeletenote.authors.collect { |c| c.name}.join(',')
I used the join cause I do not want that prints something like this ["something", "something else"], so it prints this way: something, something else.
I hope this could be useful for you, and about the controller for that view I only have:
@notes = Note.all.includes(:authors).
I know it too much time to answer but I hope someone else can find this useful.
Best Regards!