1
votes

I have a form_for that looks like this:

<%= form_for (@product||(Product.new([some params])), :remote => true, :as => :product_data, :url => {:controller => :products, action: :update}, :html => {:class => 'form-horizontal'} do |f| %>
...
<%= f.submit %>

In my controller I have 'update' action.

When the @product already exists the form is working just fine. It sends to the 'update' action in the controller. When the @product doesn't exist, it is creating a new temp product instance but submitting the form is not saving it. As a result, at page refresh the information is lost.

How can I both 'update' if @product is present and create new + update it with the form if @product is not present using the same form?

SOLVED:

In the update action of the products controller I added:

product = Product.where(some params).first rescue nil
if product.blank?
product = Product.create(some values)
end
1
can you add your controller code for create and update actions? - dax

1 Answers

4
votes

Please post you controller code also, and instead of doing

@product||(Product.new([some params])

in the view, you can assign it as

@product = Product.find(id) || Product.new([some params])

inside the controller and have the view as

<%= form_for @product, :remote => true, :as => :product_data, :url => {:controller => :products, action: :update}, :html => {:class => 'form-horizontal'} do |f| %>
...
<%= f.submit %>

And finally you are saying that the information is lost after submitting, so put a debugger in your create action and test if the data is actually saved. If nothing works, please post your controller code also.