Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails format.js and remote true

I'm working in Ruby on rails. I have successfully been able to set up a form that will render my create.js.erb. But I'm wondering if there is any way to check if the form fails to make an object? Right now, if it fails it does nothing.

My controller looks like this:

if @expansion.save
    respond_to do |format|
        format.js
        format.html { render action: "index", notice: 'Book was successfully created.' }
        format.json { render json: @book, status: :created, location: @book }
    end
else
    respond_to do |format|
        format.js 
        format.json { render json: @book.errors, status: :unprocessable_entity }
        format.html { render action: "index", notice: 'something went wrong' }


        end
end

Is there a way for me to pick up the error in create.js.erb ?

like image 325
Cinta Avatar asked Oct 18 '22 09:10

Cinta


1 Answers

You will still have access to the @expansion instance variable inside of create.js.erb. You can execute js code dependent on the existence of @expansion.errors - for example:

<% if @expansion.errors %>
  alert("You have the following errors: <%= @expansion.errors %>");
<% else %>
  // js code for successful save
<% end %>
like image 69
Fred Willmore Avatar answered Nov 03 '22 08:11

Fred Willmore