I have a really simple form that works fine until I try and resubmit. After which, it updates the record instead of creating a new one:
In my view, I have this:
#new_order_form
= render 'form'
And my form partial:
= semantic_form_for [@location, @order], :remote => true do |f|
-if @order.errors.any?
#notice{:class=>'alert alert-block alert-error fade in'}
%a{:class=>"close", :data=>{:dismiss=>"alert", :href=>"#"}}
x
%h3
= pluralize(@order.errors.count, "error")
- @order.errors.full_messages.each do |msg|
= msg
%br
%table{:class => 'table table-bordered', :style=> {width: '50%'}}
%tr
%td= f.text_field :product_order_id, :placeholder => "Order ID"
And in my create.js:
$("#new_order_form").html("<%= escape_javascript(render("form")) %>");
This works fine to create the order and renders the errors if they exist.
The problem is: if I enter another order number without refreshing the page, it updates the previously created record, instead of creating a new one.
Looking at the form code, I can see the submit action is replaced with an update.
I have tried to replace the code with this:
= semantic_form_for [@location, @order], :remote => true do |f|
#new_order_form
= render 'form', :f => f
And this in create.js
$("#new_order_form").html("<%= escape_javascript(render :partial => 'form', :locals => {:f => @order}) %>");
Which doesn’t work either and complains about an invalid text_field.
What is the best way to do this? Thanks
I am no expert on this topic but Adam’s answer seems to be correct. I assume you have something like below in your controller action:
if you have the above structure, then the create.js.erb is just passing the @order object that has been modified after @order.save call. You can just re-define it in the passed condition as follows(check line no. 4):
Now if the @order has successfully been saved, new order will be created and passed. Otherwise the old @order with validation errors will be passed. Hope this will help.