Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 从rails中的活动记录获取对象_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails 从rails中的活动记录获取对象

Ruby on rails 从rails中的活动记录获取对象,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我想获取所有被跟踪的项目,并为每个项目获取数组中的所有项目,以将其传递给部分视图。 但我不是在接收对象,而是在接收活动记录关系 这是我的密码 @row=[] @followed_blogs = Follow.where("followable_type == ?","Blog").where(follower_id: current_user.id) @followed_blogs.each do |blog| @row << Article.where("blog_id ==

我想获取所有被跟踪的项目,并为每个项目获取数组中的所有项目,以将其传递给部分视图。 但我不是在接收对象,而是在接收活动记录关系

这是我的密码

@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}
@row=[]
@followered\u blogs=Follow.where(“followable\u type==?”,“Blog”).where(follower\u id:current\u user.id)
@关注博客。每个人都做博客|
@划船
我想那是对的,你得调整一下

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

  @followed_blogs = Blog.
    where(follower_id: current_user.id).
    includes(:articles)
如果用户有正确的关联(
有很多:blog
或其他什么),它甚至可以成为

@articles = current_user.blogs.includes(:articles).
  map(&:articles).
  sort! {|a,b| a.created_at <=> b.created_at}
@articles=current_user.blogs.includes(:articles)。
地图(&:文章)。
分类{| a,b | a.created_at b.created_at}

请小心。上面的代码有味道,不能这样做。如果你有1000个博客,此代码将对数据库执行1001 select查询。
Follow
模型由我正在使用的社交gem生成,并具有预定义的关联方法,如“Blog”中的
acts\u as\u followable
,以及
User
@Mr94中的acts\u follower,然后您都已设置好。抱歉,我仍然被卡住了。我是rails新手,无法解决这个简单的问题:(最终解决了。检查我的答案,告诉我它是否会影响站点性能。
  @followed_blogs = Blog.
    where(follower_id: current_user.id).
    includes(:articles)
@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')