First, change your books_controller
so that it will always render create.js.erb
whether the book is persisted or not.
def create
@book = Book.new(params[:book])
respond_to do |format|
if @book.save
format.html { redirect_to @book, notice: 'Book was successfully created.' }
format.json { render json: @book, status: :created, location: @book }
else
format.html { render action: "new" }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
format.js
end
end
Then, in you create.js.erb
, you will want to check whether your book is persited?
or not:
<% if @book.persisted? %>
# ...
<% else %>
# display the error message
<% end %>
Let's say we are going to display the error message in a <p>
with the .errors
class:
$('<p>').text('<%= @book.errors.full_messages.to_sentence.capitalize %>')
.prepend('form');
The thing is that you will have to remove the errors paragraph every time you render create.js.erb
so that former errors won't stick around:
$('p.errors').remove();
All in all, it gives:
$('p.errors').remove();
<% if @book.persisted? %>
# ...
<% else %>
$('<p>').text('<%= @book.errors.full_messages.to_sentence.capitalize %>')
.prepend('form')
<% end %>