提交表单后仅调用一次create.js.erb

时间:2018-09-06 13:56:39

标签: ruby-on-rails simple-form

我的项目中有一个simple_form_for。我的目标是通过警报和ajax在出现错误时重新加载表单来提醒人们电子邮件已经在数据库中。第一次发送表单时,我从create.js.erb得到了很好的答复。但是,如果我第二次发送表单而没有用浏览器重新加载页面,则会考虑我的控制器create方法代码,而不考虑我的create.js.erb代码。例如,如果我在create.js.erb文件中放置了一个警报,则在我再次单击该按钮发送表单时,该警报不会弹出。你能帮我弄清楚为什么吗?

pages_controller.rb

 def create
    @email = waiting_list_params[:email]
    @waiting_user = WaitingList.new(waiting_list_params)
    respond_to do |format|
    if @waiting_user.save
        UserMailer.welcome(@email).deliver_now
        format.html { redirect_to concours_path }
        format.js
      else
        format.html { render 'pages/concours' }
        format.js { flash[:error] = @waiting_user.errors.full_messages[0] }
      end
    end
  end

create.js.erb

   function refreshForm(innerHTML) {
  const newForm = document.getElementById("concours-form");
  newForm.innerHTML = innerHTML;
}


<% if @waiting_user.errors.any? %>
  refreshForm('<%= j render "pages/concours_form" %>');
  confPopup.style.display = "none";
<% else %>
  confPopup.style.display = "flex";
<% end %>

_form.html.erb

<%= simple_form_for @waiting_user, {id: 'concours-form', url: concours_path, remote: true} do |f| %>
  <%= f.error_notification %>
  <%= f.text_field :email,
      class: "landing-form-input",
      autocomplete: "off",
      required: true,
      pattern: '[^@]+@[^@]+\.[a-zA-Z]{2,6}',
      placeholder: "Renseignez ton email ici"
    %>
  <i class="fa fa-envelope"></i>
  <%= f.hidden_field :concours_city,
      value:'',
      id: 'c-choosen-city'
    %>
  <%= f.hidden_field :source,
      value: params[:source]
    %>
  <%= f.button :submit,
      class: "landing-form-button",
      value: "Je tente ma chance !"
    %>
<% end %>

routes.rb

get 'concours', to: 'pages#concours'
post 'concours', to: 'pages#create'

0 个答案:

没有答案