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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With