0

我想计算这个块中的条目。由于 ruby​​ 块变量范围,我不处理这个代码。有什么办法解决这个问题吗?

    arr_showcase.each do |entry|
          @entry = ContestEntry.find_by_id(entry)
          if @entry.view_in_showcase == true
            @entry.view_in_showcase = false
            @entry.save
            entry_added_showcase += 1 
          else
            @entry.view_in_showcase = true
            @entry.save
            entry_removed_showcase += 1 
          end
    end
    redirect_to :back, :notice => "#{entry_added_showcase} Desings added, #{entry_removed_showcase} Designs removed."
4

2 回答 2

1

你在哪里声明entry_added_showcaseand entry_removed_showcase?你必须在块外初始化它们。

entry_added_showcase = entry_removed_showcase = 0
arr_showcase.each do |entry|
      @entry = ContestEntry.find_by_id(entry)
      if @entry.view_in_showcase == true
        @entry.view_in_showcase = false
        @entry.save
        entry_added_showcase += 1 
      else
        @entry.view_in_showcase = true
        @entry.save
        entry_removed_showcase += 1 
      end
end
redirect_to :back, :notice => "#{entry_added_showcase} Desings added, #{entry_removed_showcase} Designs removed."
于 2013-01-30T00:51:03.643 回答
0

您需要在块范围之外定义变量,如下所示:

entry_added_showcase = 0
entry_removed_showcase = 0
arr_showcase.each do |entry|
      @entry = ContestEntry.find_by_id(entry)
      if @entry.view_in_showcase == true
        @entry.view_in_showcase = false
        @entry.save
        entry_added_showcase += 1 
      else
        @entry.view_in_showcase = true
        @entry.save
        entry_removed_showcase += 1 
      end
end
redirect_to :back, :notice => "#{entry_added_showcase} Desings added, #{entry_removed_showcase} Designs removed."
于 2013-01-30T00:51:38.767 回答