Reputation: 143
I have two models Blog
and Article
as follows
class Blog < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :blog
end
And my dashboard method is as follows: [I want to fetch all the articles of all the followed blogs in @article object]
@f_blogs = current_user.followees(Blog) #Socialization gem method
@f_blogs.each do |blog|
@blogs ||= []
@blogs << Blog.where('id == ?',blog.id).includes(:articles)
end
@articles = @blogs.map(&:articles)
But this returns this error
NoMethodError: undefined method 'id' for #<Array:0x007f725c52af50>
The console gives output in ActiveRecord::Associations::CollectionProxy
How to access this array?? Need help !!
Upvotes: 0
Views: 2374
Reputation: 15957
You can refactor this a lot as you can pass an array of id's into a where clause, like so:
@blogs = Blog.where(id: @f_blogs.pluck(:id)).include(:articles)
All together that might just look like this:
@f_blogs = current_user.followees(Blog) #Socialization gem method
@blogs = Blog.where(id: @f_blogs.pluck(:id)).include(:articles)
@articles = @blogs.map(&:articles)
Though I don't totally understand what that last map
line is for as you've already eager loaded the articles for each blog.
Upvotes: 1