gpt4 book ai didi

ruby-on-rails - Ruby on Rails 中的循环内循环

转载 作者:数据小太阳 更新时间:2023-10-29 08:10:10 24 4
gpt4 key购买 nike

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

该方法的最终结果是一个数组,其中包含[问题,所有答案的总和,答案计数]

涉及3个表,每个表都有自己的 Controller 和模型

我有一个'friendships'表,它存储了用户和 friend 。

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

最后我有一个 answers 表,其中存储了友谊 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

最佳答案

friendships.answers.each

如果你的关系设置正确(has_many,belongs_to),应该可以工作

关于ruby-on-rails - Ruby on Rails 中的循环内循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9637053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com