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 では、文字列のみをサポートします。したがって、ヘルパーを次のように変更する必要がありました

  # 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

**編集:深い提案によると**

フラッシュ部分を

<% 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 に答える