简体   繁体   中英

Rails: Form partial not clearing/reloading after AJAX submission

I am trying to create a one page/view application. I have a form I submit that creates a simple tweet object:

_form.html.erb

<div id="schedule-tweet-form">
  <%= simple_form_for @tweet, :remote => true do |f| %>
    <%= f.input :text, :input_html => {:cols => 60, :rows => 6} %>
    <%= f.input :scheduled_time %>
    <%= f.button :submit, "Schedule Tweet", :class => "f-button" %>
  <% end %>
</div>

(scheduled_time is a datetime type, has multiple select boxes)

The form submission works fine and creates a row in my database without a problem. The issue is that after it submits, the data in the form is not cleared. The text for the tweet is still in the input textbox and the scheduled time still has its respective select boxes chosen.

Here is my controller:

tweets_controller.rb

class TweetsController < ApplicationController
  def index
    @tweet = Tweet.new
  end

  def create
    @tweet = Tweet.new(params[:tweet])
    @tweet.user = current_user

    respond_to do |format|
      if @tweet.save
        @tweet.tweet_at_scheduled_time
        flash[:notice] = "Tweet has been scheduled"
        format.html { render 'index' }
        format.js
      else
        format.html { render 'index' }
        format.js { render 'reload' }
      end
    end
  end
end

Here is the view where the partial is rendered:

index.html.erb

<div id="schedule-tweet-form-container">
  <%= render 'form' %>
</div>

I tried to use some jQuery to remove the form and re-render a new one once the form is submitted and the create action is called, but weirdly the form comes back with the submitted tweet's information after "append" is called (text & scheduled_time data in the input fields).

create.js.erb

<% if @tweet.save %>
  $("#schedule-tweet-form").remove();
  $('#schedule-tweet-form-container').append("<%= j render 'form' %>");
<% end %>

I have been racking my brain on this the past couple of hours and nothing else I tried from various other stack overflow questions has worked. I appreciate the help.

In your create action, after saving the tweet, you need to initialize the Tweet object again.

But in your create.js.erb you have used the @tweet, so modify the code as following

<% if @tweet.save 
     @tweet = Tweet.new
%>

  $("#schedule-tweet-form").remove();
  $('#schedule-tweet-form-container').append("<%= j render 'form' %>");
<% end %>

you should use

    format.json 

on ajax calls

check the following answer of this thread to make simple form make a json post

Is there a way to submit ajax/json requests with simple_form for Rails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM