Have error message show when form is created through AJAX
Posted
by
Railslearner
on Stack Overflow
See other posts from Stack Overflow
or by Railslearner
Published on 2012-06-19T21:13:54Z
Indexed on
2012/06/19
21:16 UTC
Read the original article
Hit count: 336
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?
© Stack Overflow or respective owner