Reputation: 466
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.
Upvotes: 3
Views: 1985
Reputation: 560
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
Upvotes: -1
Reputation: 5734
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 %>
Upvotes: 3