【问题标题】:how to create a array of hashes in Rails 4?如何在 Rails 4 中创建一个哈希数组?
【发布时间】:2015-03-25 18:51:09
【问题描述】:

我正在尝试使用我的自定义 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 方法以接受散列数组,并在每次调用时插入一个新的散列吗?

【问题讨论】:

    标签: ruby-on-rails arrays hash


    【解决方案1】:
    def toast(type, text)
      flash[:toastr] ||= []
      flash[:toastr] << { type => text }
    end
    

    【讨论】:

      【解决方案2】:

      使用Array#push

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

      使用附加 (&lt;&lt;):

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-19
        • 2011-04-20
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 2016-03-30
        • 2011-09-20
        相关资源
        最近更新 更多