每当自定义方法(进程!)在我的事务控制器中返回false或true时,我正在尝试显示一条消息。 但是,对于每个假,它只返回一次,对于每个真假只返回一次。 下面是控制器中的代码:
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!”返回的每个错误。
提前致谢。
I am currently trying to display a message every time a custom method (process!) returns either false or true within my transaction controller. However, it is only returned once for every false and once for every true. Below is the code in the controller:
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 } endBelow is the code in the 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>I assuming since I only mention it once in the application layout (one for error and one for success) it display it only once. I am wondering how would I have it to display for each false that is returned by the method "process!".
Thanks in advance.
最满意答案
布局只显示一个,因为只有一个。 无论您是否使用keep , flash都会为每个密钥存储一条消息。
因此,每次设置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?The layout displays only one, because there is only one. flash stores one message per key, regardless of whether you use keep or not.
So each time you set flash.keep[:errorTransaction], you're overwriting the previous message, not appending another one.
To solve this you could store all the messages as you iterate over the transactions, then store them on the flash all at once, something like:
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?更多推荐
发布评论