不确定为什么我一直有这个问题。无论如何,这是模型:
class Coupon < ActiveRecord::Base
has_many :coupon_codes, :dependent => :destroy
accepts_nested_attributes_for :coupon_codes, :allow_destroy => true,
:reject_if => proc { |attrs| attrs['code'].blank? }
end
class CouponCode < ActiveRecord::Base
belongs_to :coupon
end
观点(使用formtastic):
<%= semantic_form_for [:admin, @coupon] do |f| %>
<%= f.inputs "Codes" do %>
<%= f.semantic_fields_for :coupon_codes do |coupon_code| %>
<% unless coupon_code.object.new_record? %>
<%= coupon_code.input :_destroy, :as => :boolean %>
<% else %>
<%= coupon_code.input :code %>
<% end %>
<% end %>
<% end %>
<%= f.buttons %>
<% end %>
对控制器的帖子调用:
Started POST "/admin/coupons/12" for 127.0.0.1 at Sat Apr 02 14:18:47 +0200 2011
Processing by Admin::CouponsController#update as HTML
Parameters: {"commit"=>"Update Coupon", "coupon"=>{"name"=>"Test2",
"coupon_codes_attributes"=>{"0"=>{"id"=>"13"}, "1"=>{"code"=>"Silly4"}},
"available"=>"true", "num_free_months"=>"0", "auto_generate_codes"=>"false",
"num_codes"=>"", "num_discount_months"=>"999", "discount_type"=>"value",
"code_prefix"=>"", "users_per_code"=>"10", "monthly_discount"=>"5.0"},
"authenticity_token"=>"f2lPUs2bsDBwlTtNJP63+gnub04nz8PR/+NKzs7ZY9Y=", "utf8"=>"✓",
"id"=>"12", "_destroy"=>"0"}
现在,我注意到那里有一个虚假的_destroy参数。所以我将表单代码更改为:
<%= coupon_code.input :_destroy, :as => :select, :include_blank => false, :collection => [ ["No", 0], ["Yes", 1] ] %>
绕过那个bug。现在我明白了:
Started POST "/admin/coupons/12" for 127.0.0.1 at Sat Apr 02 14:25:56 +0200 2011
Processing by Admin::CouponsController#update as HTML
Parameters: {"commit"=>"Update Coupon", "coupon"=>{"name"=>"Test2",
"coupon_codes_attributes"=>{"0"=>{"id"=>"13", "_destroy"=>"1"}, "1"=>{"id"=>"14",
"_destroy"=>"0"}, "2"=>{"code"=>""}}, "available"=>"true", "num_free_months"=>"0",
"auto_generate_codes"=>"false", "num_codes"=>"", "num_discount_months"=>"999",
"discount_type"=>"value", "code_prefix"=>"", "users_per_code"=>"10",
"monthly_discount"=>"5.0"},
"authenticity_token"=>"f2lPUs2bsDBwlTtNJP63+gnub04nz8PR/+NKzs7ZY9Y=", "utf8"=>"✓",
"id"=>"12"}
但仍然......没有被删除!
我确信它很简单,但是,我设置了allow_destroy ......还有什么需要在那里!?
答案 0 :(得分:2)
问题在于您使用
:reject_if => proc { |attrs| attrs['code'].blank? }
然后你发送这些数据:
{"id"=>"13", "_destroy"=>"1"}
因此reject_if
“验证”返回false,因为code
为空。
您还需要在表单中传递code
:
<% unless coupon_code.object.new_record? %>
<%= coupon_code.input :_destroy, :as => :boolean %>
<%= coupon_code.input :code, :as => :hidden %> # or how it use hidden field with formastic
<% else %>
<%= coupon_code.input :code %>
<% end %>
或更改reject_if
:reject_if => proc { |attrs| attrs['code'].blank? && !(attrs[:_destroy] == "true" || attrs[:_destroy] == "1") }
最后解决方案小清洁工