0

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}
1
  • Please read this carefully. The code above smells, it mustn’t be done that way. If you have, say, 1000 blogs, this code will execute 1001 select query against the database. Commented Aug 21, 2015 at 14:26

2 Answers 2

2
@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}
Sign up to request clarification or add additional context in comments.

4 Comments

the Follow model is generated by the socialization gem that I am using and have predefined methods for associations like acts_as_followable in 'Blog' and acts_as_follower in User
@Mr94 then you are all set up.
Sorry but I am still stuck. I am new to rails and can't figure out solution of this simple problem :(
Solved it finally. Check my answer and tell me if it will effect the sites performance.
0
@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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.