Flash сообщения (ajax)

Можно ли показать ошибки формы во флэш-сообщениях в ajax? Я хочу показать ошибки формы, когда невозможно сохранить запись из-за уникального поля.

мой индекс

<!--<p id="notice"><%= notice %></p>-->
<h1>Empresas</h1>
<style>
.container {
}

</style>
<div class="container">
  <div class="row">
    <div class="text-center">
      <!-- Button trigger modal -->
      <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#mynewempresa">
        Nueva empresa
      </button>
    </div>
  </div>

  <br>
  <br>



  <table id="empresas" class="display"><!--el id empresas es de datatables referenciado en empresas.coffe y display class es una clase de datatables-->
  <thead>

    <tr><!--active es para sombrear la fila-->
      <th>Clave</th>
      <th>Empresa</th>
      <th>Acción</th>
      <th></th>

    </tr>
  </thead>
    <tbody id="container_empresas">
      <%= render @empresas %><!--carga todos los empresas-->
</tbody>


</table>
<!-- Modal create action -->
<%= form_for(@empresa, remote: true, html: {class: "form-horizontal formulario-validado-create"}) do |f| %> <!--ajax remote: true-->
  <div class="modal fade" id="mynewempresa" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">Agregar empresa</h4>
        </div>
        <div class="modal-body">

          <div id="flash_messages_placeholder" >

           </div>

          <div class="form-group">
            <%= f.label :IdEmpresa, "Clave:", class: "control-label col-md-2 " %>
            <div class="col-md-3">
              <%= f.text_field :IdEmpresa, class: "form-control empresa_clave",autofocus: true, minlength: "1", required: "true"  %>
            </div>
              <%= f.label :Empresa, "Empresa:", class: "control-label col-md-2" %>
            <div class="col-md-5">
              <%= f.text_field :Empresa, class: "form-control empresa_empresa",minlength: "4", required: "true"  %>
            </div>
          </div>





        </div>

        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal" id="mynewempresaclose">Cerrar</button>
          <%= submit_tag "Crear", class: "btn btn-primary"%>
        </div>
      </div>
    </div>
  </div>
<%end%>
</div>

мой контроллер

class EmpresasController < ApplicationController
  before_action :set_empresa, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_usuario!


  # GET /empresas
  # GET /empresas.json
  def index
    @empresas = Empresa.all
    @empresa = Empresa.new
    respond_to do |format|
      format.html
      format.csv { send_data @empresas.to_csv}
      format.xls #{ send_data @empresas.to_csv(col_sep: "t") }
    end
  end

  def import
    Empresa.import(params[:file])
    redirect_to empresas_path, notice: "Sucursales importadas."
  end

  # GET /empresas/1
  # GET /empresas/1.json
  def show
  end

  # GET /empresas/new
  def new
    @empresa = Empresa.new
  end

  # GET /empresas/1/edit
  def edit
  end

  # POST /empresas
  # POST /empresas.json
  def create
    @empresa = Empresa.new(empresa_params)
    format.js { render 'shared/error_messages_js'}

    respond_to do |format|
      if @empresa.save
        format.html { redirect_to @empresa, notice: 'Empresa was successfully created.' }
        format.json { render :show, status: :created, location: @empresa }
        format.js {flash.now[:notice] = 'La Sucursal se ha creado de forma exitosa.'} #ajax


      else
        format.html { render :new }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
        format.js {flash.now[:alert] = 'Error al crear la sucursal.'} #ajax


      end
    end
  end

  # PATCH/PUT /empresas/1
  # PATCH/PUT /empresas/1.json



  def update
    respond_to do |format|
            ##use locals if multiple models
        ##add model errors
        flash.now[:error] = @empresa.errors.full_messages
        ##flash.now[:error] = @model.errors.full_messages.to_sentence

      if @empresa.update(empresa_params)
        format.html { redirect_to @empresa, notice: 'Empresa was successfully updated.' }
        format.json { render :show, status: :ok, location: @empresa }
        format.js {flash.now[:notice] = 'La Sucursal se ha actualizado de forma exitosa.'} #ajax


      else
        format.html { render :edit }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
        format.js {flash.now[:alert] = 'Error al actualizar la sucursal.'} #ajax


      end
    end
  end

  # DELETE /empresas/1
  # DELETE /empresas/1.json
  def destroy
    @empresa.destroy
    respond_to do |format|
      format.html { redirect_to empresas_url, notice: 'Empresa was successfully destroyed.' }
      format.json { head :no_content }
      format.js {flash.now[:notice] = 'La Sucursal se ha borrado de forma exitosa.'} #ajax


    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_empresa
      @empresa = Empresa.find(params[:idempresa])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def empresa_params
      params.require(:empresa).permit(:IdEmpresa, :Empresa)
    end
end

мой помощник по приложениям:

module ApplicationHelper
  ###application_helper.rb
   def flash_display
       Rails.logger.info "show flash message ajax======== "
     response = ""
     flash.each do |name, msg|
       msg=msg ###"<i class='fa fa-quote-left fa-border'></i>"+msg+"<i class='fa fa-quote-right fa-border'></i>"+"<button type='button' class='close' title='hide' data-dismiss='alert'><i class='fa-times-circle-o fa pull-right'></i></button>".html_safe
       response = response +
       content_tag(:div, msg, :id => "flash_#{name}",:class=>"alert alert-danger") do
           "#{msg}".html_safe
       end
     end
     flash.discard
     response
   end
end

##views / shared / error_messages_js.Эрб

$('#flash_messages_placeholder').html("<%= escape_javascript raw(flash_display) %>");

1 ответ

  1. Да..это возможно..

    во-первых, создайте вспомогательный метод, который может использоваться для отображения flash-сообщений на представлении.

     ###application_helper.rb
        def flash_display
            Rails.logger.info "show flash message ajax======== "
          response = ""
          flash.each do |name, msg|
            msg=msg ###"<i class='fa fa-quote-left fa-border'></i>"+msg+"<i class='fa fa-quote-right fa-border'></i>"+"<button type='button' class='close' title='hide' data-dismiss='alert'><i class='fa-times-circle-o fa pull-right'></i></button>".html_safe
            response = response + 
            content_tag(:div, msg, :id => "flash_#{name}",:class=>"alert alert-danger") do 
                "#{msg}".html_safe  
            end     
          end
          flash.discard
          response
        end
    

    Во-вторых,в коде контроллера ,где вы размещаете данные, используяremote=true, обработайте ответ js, как показано ниже.

         respond_to do |format|
              ##use locals if multiple models
            ##add model errors
            ##flash.now[:error] = @model.errors.full_messages
            ##flash.now[:error] = @model.errors.full_messages.to_sentence
            flash.now[:error]="You cannot edit this Page"
            format.js { render 'shared/error_messages_js'}
           end
    
         ##views/shared/error_messages_js.erb
            $('#flash_messages_placeholder').html("<%= escape_javascript raw(flash_display) %>");
    

    Итак, выше js.erb-файл будет искать пустой заполнитель для отображения flash-сообщений.Таким образом, ваша форма также должна иметь заполнитель

        ###_form.html.erb
        <form action="<%= post_data_path(current_user)%>" method="post" data-remote="true">
        <div id="flash_messages_placeholder" > </div>
    
        ##input fields/submit button goes here
       <%end%>
    

    Надеюсь, это поможет 🙂