Reputation: 27212
I have a page called /add
that you can add a Dog
on and the form is in its own partial. I'm using Simple Form and Twitter Bootstrap. I added the files for the main Bootstrap but use a gem for simple_form to work with it just so you know.
DogsController
# new.js.erb (deleted new.html.erb)
def new
@dog = Dog.new
respond_to do |format|
format.js
end
end
# create.js.erb
def create
@dog = current_user.dogs.new(params[:dog])
respond_to do |format|
if @dog.save
format.html { redirect_to add_url, notice: 'Dog was successfully added.' }
format.json { render json: @dog, status: :created, location: @dog}
format.js
else
format.html { render 'pages/add' }
format.json { render json: @dog.errors, status: :unprocessable_entity }
end
end
end
dogs/_form.html.erb
<%= simple_form_for(@dog, :remote => true) do |f| %>
<%= render :partial => "shared/error_message", :locals => { :f => f } %>
<%= f.input :name %>
<%= f.button :submit, 'Done' %>
<% end %>
This line: <%= render :partial => "shared/error_message", :locals => { :f => f } %>
Is for bootstrap so it renders the errors html correctly.
PagesController
def add
respond_to do |format|
format.html
end
end
pages/add.html.erb
<div id="generate-form">
</div>
dogs/new.js.erb
$("#generate-form").html("<%= escape_javascript(render(:partial => 'dogs/form', locals: { dog: @dog })) %>");
Now how would I get this to render the error partial as if it was still on my dogs/new.html.erb
since its being created through AJAX? I don't need client side validations do I?
EDIT
shared/_error_message.html.erb
<% if f.error_notification %>
<div class="alert alert-error fade in">
<a class="close" data-dismiss="alert" href="#">×</a>
<%= f.error_notification %>
</div>
<% end %>
Upvotes: 1
Views: 410
Reputation: 512
Through our chat you mentioned you also had a create.js.erb and that file was clearing out the form.
making the the create.js the same as new.js.erb : $("#generate-form").html("<%= escape_javascript(render(:partial => 'dogs/form', locals: { dog: @dog })) %>");
made it work.
Upvotes: 2
Reputation: 512
You don't have to do client side validations. But should,it is common to disable the submit button via js until client side validation is met. also I would not delete the new.html.erb incase a client doesn't.have js turned on. I think your add may need format.js to your add and remote = true to your shared errors partial call
Upvotes: 2