提交表单后,从Rails控制器调用模式

时间:2020-07-28 19:36:27

标签: ruby-on-rails ruby

我正在尝试在提交表单并创建客户之后从控制器调用模式。我尝试浏览,但没有找到答案。

这是我的控制者:

def create
   @customer = Customer.new(packets_params)

   respond_to do |format|
    if @customer.save
      UserMailer.with(customer: @customer).welcome_email.deliver
           
      format.html { redirect_to(new_customer_path) }
    else
      format.html { render action: 'new' }
    end
  end
end

能不能帮我,非常感谢。

1 个答案:

答案 0 :(得分:0)

如果您想避免任何前端渲染,则可以返回一个JSON响应,其中包含在erb文件中定义的模式的HTML:

def create
   @customer = Customer.new(packets_params)

    if @customer.save
      UserMailer.with(customer: @customer).welcome_email.deliver

      render(
        modal: render_to_string('welcome_modal.html.erb'),
        status: :created
      )
    else
      render(
        errors: @customer.errors
        status: :bad_request
      )
    end
  end
end

然后您的模态模板可能如下所示:

# app/views/mycontroller/_welcome_modal.html.erb
<div class="modal welcome-modal" tabindex="-1" data-backdrop="static" role="dialog">
  <h1> Welcome! </h1>
</div>

请确保您的模板文件位于视图所需的标准目录结构中,并以_为前缀表示该文件是部分文件。

在前端,您将以AJAX调用的形式发出请求,然后将模式呈现到屏幕上或处理返回的错误:

// some JS file - implementation is proof of concept and not clean

$('form').on('submit', function () {
  var data = $('form').serialize();
  $.post('/customer', data)
    .done(function (res) { /* render modal */ }
    .error(function (error) { /* handle errors */ }

});
相关问题