1

我正在尝试使用 Bootstrap 样式向用户显示带有颜色的 Flash 消息。

控制器

  def create
    @category = Category.new(category_params)

    # Assigning default values
    @category.status = 1.to_i

    if @category.save
      redirect_to admin_categories_path, :flash => { :success => "Category was successfully created." }
    else
      flash[:error] = "Category could not be save. Please try again."
      render :new
    end
  end

看法

<%= render 'admin/partials/flash_message' %>

部分的

<% if flash.present? %>
<%= flash.inspect %>
  <% flash.each do |key, value| %>
    <div class="<%= flash_class(key) %> fade in widget-inner">
      <button type="button" class="close" data-dismiss="alert">×</button>
      <%= value %>
    </div>
  <% end %>
<% end %>

帮手

  # Flash Messages
  def flash_class(level)
    case level
      when :notice then "alert alert-info"
      when :success then "alert alert-success"
      when :error then "alert alert-error"
      when :alert then "alert alert-error"
    end
  end

输出

我无法将密钥传递给辅助函数。我假设它发送空白。这是输出的 HTML

<div class=" fade in widget-inner">
      <button data-dismiss="alert" class="close" type="button">×</button>
      Category could not be save. Please try again.
    </div>

我无法弄清楚为什么 foreach 无法提取键值对。检查时我得到以下信息

#<ActionDispatch::Flash::FlashHash:0x007fc0e74dfa58 @discard=#<Set: {}>, @flashes={"error"=>"Category could not be save. Please try again."}, @now=nil> 
4

1 回答 1

0

在 Rails 4 中,它只支持字符串。所以我不得不将 Helper 更改为以下

  # Flash Messages
  def flash_class(level)
    case level
      when 'notice' then "alert alert-info"
      when 'success' then "alert alert-success"
      when 'error' then "alert alert-danger"
      when 'alert' then "alert alert-warning"
    end
  end

**编辑:根据深度建议**

通过将 Flash Partial 更改为

<% if flash.present? %>
  <% flash.each do |key, value| %>
    <div class="alert alert-<%= key %> fade in widget-inner">
      <button type="button" class="close" data-dismiss="alert">×</button>
      <%= value %>
    </div>
  <% end %>
<% end %>

通过按如下方式扩展 BootStrap 类,我们可以一起消除 Helper 类。

alert-notice { @extend .alert-info; }
alert-error { @extend .alert-danger; }
于 2014-06-21T04:43:53.397 回答