Reputation: 143
I want to fetch all the items being followed and the for each item I want to fetch all of it's articles in an array to pass it to the view partial. But I am not receiving objects rather I am receiving Active Record relation
Here is my code
@row=[]
@followed_blogs = Follow.where("followable_type == ?","Blog").where(follower_id: current_user.id)
@followed_blogs.each do |blog|
@row << Article.where("blog_id == ?",blog.followable_id)
end
@articles = @row.sort! {|a,b| a.created_at <=> b.created_at}
Upvotes: 0
Views: 53
Reputation: 143
@f_blogs = Follow.where('followable_type == ?',"Blog").where('follower_id == ?', current_user.id).pluck('followable_id')
@articles = Article.having(blog_id: @f_blogs).group('id')
Upvotes: 0
Reputation: 4478
@followed_blogs = Follow.
where(followable_type: "Blog").
where(follower_id: current_user.id).
includes(:articles)
@row = @followed_blogs.map(&:articles)
@articles = @row.sort! {|a,b| a.created_at <=> b.created_at}
This might work better, assuming you've got the relations set correctly between Follow
and Article
.
class Follow < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :follow, as: blog
end
I think that's right, you'll have to tweak it. http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
With the polymorphic association set up properly, the first line becomes:
@followed_blogs = Blog.
where(follower_id: current_user.id).
includes(:articles)
And if User has the correct association (has_many :blogs
or something), it can even become
@articles = current_user.blogs.includes(:articles).
map(&:articles).
sort! {|a,b| a.created_at <=> b.created_at}
Upvotes: 2