Ruby on rails 将闪烁转换为标准阵列

Ruby on rails 将闪烁转换为标准阵列,ruby-on-rails,Ruby On Rails,我开始学习RubyonRails,就像现在一样。但是我很难在那些flash会议上绞尽脑汁 我宁愿让它像这样工作: flash[:alert] << "first alert message" flash[:alert] << "second alert message" flash[:alert].class == Array flash[:alert]正如@lucapete所问的,你想做什么?如果要在多行上显示多条消息,可以显式添加新行: flash[:alert

我开始学习RubyonRails,就像现在一样。但是我很难在那些flash会议上绞尽脑汁

我宁愿让它像这样工作:

flash[:alert] << "first alert message" 
flash[:alert] << "second alert message"
flash[:alert].class == Array

flash[:alert]正如@lucapete所问的,你想做什么?如果要在多行上显示多条消息,可以显式添加新行:

flash[:alert] += "\nSecond message."
或者你应该能够做这样的事情:

flash[:alert] = []
flash[:alert] << "Message 1"
class ApplicationController

  def add_to_flash_array key, value
    # set empty array as default value
    flash[key] ||= [] 

    if flash[key].is_a? Array
      flash[key] << value
    else # somebody set a value from underneath this method, enter panic mode
      raise "flash['#{key}'] is not an array!"
    end
  end
end

# usage

add_to_flash_array :alert, 'Message 1'
add_to_flash_array :alert, 'Message 2'

或者自动将其设置为数组:

Array(flash[:error])

然后,您可以以任何方式循环它。

您可以在应用程序控制器中编写一个helper方法。例如,像这样:

flash[:alert] = []
flash[:alert] << "Message 1"
class ApplicationController

  def add_to_flash_array key, value
    # set empty array as default value
    flash[key] ||= [] 

    if flash[key].is_a? Array
      flash[key] << value
    else # somebody set a value from underneath this method, enter panic mode
      raise "flash['#{key}'] is not an array!"
    end
  end
end

# usage

add_to_flash_array :alert, 'Message 1'
add_to_flash_array :alert, 'Message 2'
类应用程序控制器
def add_to_flash_数组键,值
#将空数组设置为默认值
闪光[键]| |=[]
如果闪烁[键],是否为a?排列

闪[键]你想做什么?有两条消息?“但是,它不工作。”-没有有效的错误描述。塔斯:没有,非常糟糕的错误描述。我要找的是一个地方来将flash[:alert]转换成数组。某种结构。如前所述,我在Pre_filter中尝试了它,但在我向警报中添加flash之前,它没有被调用。卢卡佩特:我正试图让flash[:alert](或任何其他flash)表现为数组(或散列)。是的,这是正确的。但我不想一直将flash[:error]转换为数组,否则我必须知道我将第一个flash发送到哪里,并将其转换为那里的数组。因此,我正在寻找一个排序结构来放入代码数组(flash[:error])。