从我的 .each 循环中获取流氓迭代 [英] Getting a rogue iteration from my .each loop

查看:42
本文介绍了从我的 .each 循环中获取流氓迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在 Rails 上学习 ruby​​ 并大致遵循本指南:http://guides.rubyonrails.org/getting_started.html

I'm just learning ruby on rails and following this guide roughly: http://guides.rubyonrails.org/getting_started.html

我有关于成就结果的循环(指南示例中的评论):

I have this loop on achievement results (comments in the guide example):

<h2>Completed results (<%= @achievement.achievement_results.count %>)</h2>
<% @achievement.achievement_results.each do |result| %>
<p>
    <b>ID:</b>
    <%= result.id %>
</p>
<p>
    <b>Success:</b>
    <%= result.success %>
</p>
<p>
    <b>User:</b>
    <%= result.user_id %>
</p>
<p><%= link_to 'Delete', [result.achievement, result], confirm: 'Are you sure?', method: :delete %></p>
<hr/>
<% end %>

这是在成就的显示视图中,当我加载该视图时,我看到循环的额外迭代,结果字段为空值.即使数组是 [] 也会发生这种情况(使用 rails 控制台检查以确保数组为空).

This is in the show view for an achievement and when I load that view, I see an extra iteration of the loop with null values for the result fields. This happens even when the array is [] (checked using rails console to make sure that the array is empty).

成就模型:

class Achievement < ActiveRecord::Base
  has_many :achievement_results, :dependent => :destroy
end

推荐答案

你有没有像 @achievement.achievement_results.build 这样的一行被调用到某个地方(可能是控制器,或者某个地方的某个表单)?).这将解释为什么 count 返回不同的数字(因为 count 不像 size 那样被缓存)以及为什么这些值为空.

Do you have a line such as @achievement.achievement_results.build being called somewhere (maybe the controller, or in a form somewhere?). This would explain why count returns a different number (as count is not cached like size) and why the values are null.

如果您确实有该行,将其更改为 AchievementResults.new(:achievement => @achievement) 可能会让您解决问题.

If you do have that line, changing it to AchievementResults.new(:achievement => @achievement) will probably sort you out.

这篇关于从我的 .each 循环中获取流氓迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆