从活动记录中获取对象

时间:2015-08-21 14:17:49

标签: ruby-on-rails ruby activerecord

我想获取所有正在关注的项目以及我想要获取数组中所有文章的每个项目以将其传递给视图部分。 但我没有收到对象而是收到了Active Record关系

这是我的代码

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

2 个答案:

答案 0 :(得分: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}

假设您已在FollowArticle之间正确设置了关系,那么这可能会更好。

class Follow < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :follow, as: blog
end

我认为没错,你必须调整它。 http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

正确设置多态关联后,第一行变为:

  @followed_blogs = Blog.
    where(follower_id: current_user.id).
    includes(:articles)

如果用户具有正确的关联(has_many :blogs或其他内容),它甚至可以成为

@articles = current_user.blogs.includes(:articles).
  map(&:articles).
  sort! {|a,b| a.created_at <=> b.created_at}

答案 1 :(得分: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')
相关问题