1

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
4

1 回答 1

4

请也发布您的控制器代码,而不是这样做

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

在视图中,您可以将其分配为

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

在控制器内部并将视图视为

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

最后你说提交后信息丢失了,所以在你的创建操作中放置一个调试器并测试数据是否真的保存了。如果没有任何效果,请同时发布您的控制器代码。

于 2013-10-30T17:43:32.790 回答