2012-11-18 112 views
0

我目前正试图在每次自定义方法(process!)在我的事务控制器中返回false或true时显示消息。但是,每一次错误只返回一次,每一次错误只返回一次。下面是在控制器代码:循环中的Flash消息将不会显示多次

def execute_all 
@transaction = Transaction.find(:all) 
#Execute all transactions 
@transaction.each do |t| 
     if (t.process!) 
      #flash.keep[:noticeTransaction] = 'Transaction number: ' + t.id.to_s + ' executed Successfully!' 
      else 
      flash.keep[:errorTransaction] = 'Transaction cannot be executed -> Transaction Id: ' + t.id.to_s 
     end 
     end 
respond_to do |format| 
     format.html { redirect_to transactions_url } 
     format.json { head :no_content } 
    end 

下面是在application.html.erb

<html> 
<head> 

</head> 
<body> 
<p style="color:red" class="error"><%= flash[:errorTransaction] %></p> 
<p style="color:green" ><%= flash[:noticeTransaction] %></p> 

<%= yield %> 

</body> 

我假设,因为我只是在应用程序布局一次提到它的代码(一个出错,一个成功),它只显示一次。我想知道如何让它显示由“process!”方法返回的每个false。

在此先感谢。

回答

0

布局显示只有一个,因为只有一个。无论您是否使用keepflash每个密钥都会存储一条消息。

因此,每次您设置flash.keep[:errorTransaction]时,您将覆盖上一条消息,而不是附加另一条消息。

为了解决这个问题,你遍历交易,你可以存储所有信息,然后将它们存储在flash一下子,像:

messages = [] 
@transaction.each do |t| 
    if (t.process!) 
    messages << '<div class="some-class">your message in a wrapper</div>' 
    end 
end 
flash.keep[:errorTransaction] = messages.join if messages.any? 
+0

有道理和阵列工作。谢谢! – Alex