1

我在初学者级别有一个非常复杂的查询,我无法解决。在本地机器上,我的页面加载时间约为 6 7 秒。

查询类似于用户

self.groups.collect(&:reports).flatten.paginate

现在我运行一个类似于以下内容的循环:

reports.each do |report|
  report.name

  report.user.name
  report.user.image.attachment.url(:thumb)   #User has_one :image , Image belongs_to :user

  report.questions.each do |question|
    question.name 

    question.answers.each do |answer|
      answer.name
    end
  end

  report.comments.each do |comment|
    comment.name 
    comment.user.name
    comment.user.image.attachment.url(:thumb)   #User has_one :image , Image belongs_to :user
  end

end

它有很多嵌套循环,需要大量使用包含,但我无法弄清楚我应该继续使用哪种方式。我之前的问题是N+1 在与活动记录的关系中?

- - - - - - - - - 编辑 - - - - - - - - -

我能做到

self.groups.includes(:reports => [:user, :questions]) 

或者

self.groups.includes(:reports => [:user => [:image]]) 

但不是

 self.groups.includes(:reports => [:user => [:image], :questions]) 

这有什么问题?

- - - - - - - - - 编辑 - - - - - - - - -

self.groups.includes(:reports => [:questions, :user => [:image]]).collect(&:reports).flatten.paginate(:page => page, :per_page => 6)    

根据子弹宝石( https://github.com/flyerhzm/bullet ) ,这似乎对我有用,没有额外/更少的急切加载,但加载查询仍然需要大约 10 秒,它就像一个巨大的巨大加载。任何进一步的改进建议?

- - - - - - - - - 编辑 - - - - - - - - -

 self.groups.includes(:reports => [:questions, .........]).collect(&:reports).paginate

变成

self.group_reports.includes(:questions, ....... ).paginate

帮了很多忙

用户模型中定义了类似的东西

has_many :reports
has_many :group_reports, :through => :groups, :source => :reports
4

1 回答 1

0

尝试使用哈希:self.groups.includes(:reports => [:questions, {:user => :image}])

于 2012-12-22T19:03:23.867 回答