【问题标题】:Loop within loop within loop on Ruby on RailsRuby on Rails 中的循环内循环
【发布时间】:2012-03-27 01:56:18
【问题描述】:

我希望我网站的用户看到他的朋友在不同问题上给出的平均答案(1 到 100)。

这个方法的最终结果是一个数组,里面有[question, sum of all answers, answer count]

涉及 3 个表,每个表都有自己的控制器和模型

我有一个“友谊”表,用于存储用户和朋友。

然后是一个问题表,其中只有问题及其 ID。

最后我有一个答案表,其中存储了友谊 ID、问题 ID 和给出的答案。

我找到了一种方法(虽然还没有尝试过):我寻找用户的友谊,然后寻找每个友谊给出的答案,然后检查每个问题以将其添加到一个最终的数组。

q_and_a = Array.new
friendships = Friendship.find_by_user_id(current_user.id)
friendships.each do |friendship|
    answers = Answer.find_by_friendship_id(friendship.id)
    answers.each do |answer|
        q_and_a.each do |array|
            question = Question.find_by_id(answer.question_id)
            if array[0] == statement.description
                array[1] = array[1] + answer.value
                array[2] = array[2] + 1
            else
                q_and_a << [ question.description, answer.value, 1 ]
            end
        end
    end
end

太可怕了,我希望有更好的方法来做到这一点?更何况友谊表和答案表必然会有数十万条记录,并且会继续增长

编辑 如下所述,我建立了关联,但我没有使用它们!菜鸟的错误。 最终的工作代码是:

@q_and_a_them = Array.new
user_answers = current_user.friends.collect { |c| c.answers }.flatten
user_answers.each do |a|
  question = Question.find_by_id(a.question_id)
  if @q_and_a_them.empty?
    @q_and_a_them << [ question.description, a.value, 1 ]
  else
    @q_and_a_them.each do |q|
      if q[0] == question.description
        q[1] = q[1] + a.value
        q[2] = q[2] + 1
      else
        @q_and_a_them << [ question.description, a.value, 1 ]
      end
    end
  end
end

加上friendship.rb上的配置

has_many :relationships
has_many :answers, :through => :relationships

【问题讨论】:

  • 你的后端是传统的SQL数据库吗?这确实可能会出现“大规模”问题,这可能会导致使用单独的“friendship_stats”表进行优化,该表最终以“接近”实时的方式保持一致/更新。
  • 这是一个 sqlite3,我正在开始开发。你的意思是我应该有一个一直在后台运行上述代码的“friendship_stats”表?
  • 不一定是“一直”,而是在后台的某个时间间隔,这样用户会看到大致最新的版本。就像每次登录时不会重新计算用户在 SO 上的声誉一样,有些事情计算一次并缓存是有意义的。
  • 什么是statement.description?
  • statement.description 是 question.description。谢谢皮特

标签: ruby-on-rails ruby arrays loops each


【解决方案1】:

嗯

friendships.answers.each

应该有效,因为您的关系设置正确(has_many,belongs_to)

【讨论】:

    【解决方案2】:

    内部逻辑稍微复杂一些,但是你可以使用#flat_map减少一层深度:

    friendships.flat_map { |f| Answer.find_by_friendship_id f.id }.each do |answer|
       q_and_a.each do |array|
         # Blah blah.
       end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多