другая проблема accepts_nested_attributes_for - не удаление - PullRequest
1 голос
/ 02 апреля 2011

Не уверен, почему у меня продолжают возникать проблемы с этим.Во всяком случае, вот модели:

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] ] %>

Чтобы обойти эту ошибку.И теперь я вижу:

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 ... что еще нужно длябыть там!?

1 Ответ

2 голосов
/ 02 апреля 2011

Проблема в том, что вы используете

: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") }

последнее решение немного чище

...