2016-12-14 17 views
1

私はモーダルを持っていますが、モーダルを閉じると、アクションが実行されたことを確認するためのフラッシュメッセージを表示する必要があります。このコードがある瞬間ですが、 tは "トースト" またはマテリアライズまたはブートストラップのような "警告" を持って、ここに私のコードです:ajaxでRailsを使ってフラッシュメッセージを表示する方法は?

レイアウト/ alerts.html.erb

<% if notice %> 
    <div class="callout small notice"> 
    <%= notice %> 
    </div> 
<% end %> 

<% if alert %> 
    <div class="callout small alert"> 
    <%= alert %> 
    </div> 
<% end %> 

contact_form.html.erb

<div class="callout"> 
    <h6>Formulario de contacto</h6> 

    <%= form_for @contact, remote: true, authenticity_token: true do |f| %> 
    <% if @contact.errors.any? %> 
     <div id="error_explanation"> 
     <h2><%= pluralize(@contact.errors.count, "error") %> prohibited this @contact from being saved:</h2> 

     <ul> 
     <% @contact.errors.full_messages.each do |message| %> 
      <li><%= message %></li> 
     <% end %> 
     </ul> 
     </div> 
    <% end %> 

    <div class="field"> 
     <%= f.text_field :title, placeholder: "Title" %> 
    </div> 

    <div class="field"> 
     <%= f.text_area :content, placeholder: "Content", :rows => 10, :cols => 120 %> 
    </div> 

    <div class="actions"> 
     <%= f.submit "Send", class: "button" %> 
    </div> 
    <% end %> 
</div> 

create.js.erb

<% if @contact.errors.empty? %> 
    $('#exampleModal1').foundation('close'); 
    $(".notice").html('<%= j render partial: "layouts/alerts" %>'); 
<% else %> 
    $(".alert").html('<%= j render partial: "layouts/alerts" %>'); 
<% end %> 

contact_controller.rbは

def create 
    @contact = Contact.new(contact_params) 
    @contact.email = current_enterprise.email 

    respond_to do |format| 
     if @contact.save 
     ContactMailer.contact_email(@contact).deliver 
     format.html { redirect_to root_path, notice: 'Contact was successfully created.' } 
     format.js { flash[:notice] = "The message was sent" } 
     format.json { render :show, status: :created, location: @contacts } 
     else 
     format.html { render :new } 
     format.json { render json: @contact.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

答えて

1

あなたはすでにこれを解決している疑いの余地はなく、他の誰のために人には、Googleを経由して、ここで終わる:

あなたのコードはうまくいくはずですが、alerts.html.erb部分にnoticeまたはalertを渡す必要があります。

​​

また、セーブ失敗したために、あなたのコントローラにflash[:alert]に値を設定する必要があるかもしれません。

関連する問題