简体   繁体   中英

Getting objects from active record in rails

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}
@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}
@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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM