如何在Rails 4中创建哈希数组?

时间:2015-03-25 18:51:10

标签: ruby-on-rails arrays hash

我正在尝试使用自定义toastr通知

来实现此行为

这就是我所拥有的

  def toast(type, text)
   flash[:toastr] = { type => text }
  end

我在我的控制器中这样称呼

toast('success',"this is a message")

它会像我这样输出到我的模板

        <% flash[:toastr].each do |type, message| %>
            toastr.<%= type %>('<%= message %>')
        <% end %>

然而它只输出1条消息

现在这里是我正在尝试制作的功能,它显示多个Flash消息 http://tomdallimore.com/blog/extending-flash-message-functionality-in-rails/

因为以下方法而起作用

def flash_message type, text
  flash[type] ||= []
  flash[type] << text
end

每当你调用#flash_message时,它会将flash消息保存在一个数组中,我可以在数组上使用for each来显示它。

我无法将#toast转换为#toast当前正在执行此操作

flash[:toastr] = {'success' => "this is a message"}

我想这样做

flash[:toastr] = [{'success' => "this is a message'},{'error' => "problem!"}]

有人可以帮我修改toast方法以接受哈希数组,并在每次调用时插入新的哈希值吗?

2 个答案:

答案 0 :(得分:1)

def toast(type, text)
  flash[:toastr] ||= []
  flash[:toastr] << { type => text }
end

答案 1 :(得分:0)

使用Array#push

def toast type, text
  flash[:toastr] ||= []
  flash[:toastr].push({ type => text })
end

使用追加(<<):

def toast type, text
  flash[:toastr] ||= []
  flash[:toastr] << { type => text }
end