我正在尝试接受_nested_attributes_for,但它没有正确拒绝。以下是两种模式:
民意测验
class Poll < ActiveRecord::Base
has_many :poll_options, :dependent => :destroy
accepts_nested_attributes_for :poll_options, :reject_if => proc { |attributes| attributes['title'].blank? }
POLLOPTION
class PollOption < ActiveRecord::Base
belongs_to :poll
我使用3个poll_options构建一个民意调查表单,但如果你填写3个中的2个,则不会删除第3个。这是日志:
Started POST "/polls/50" for 127.0.0.1 at Sun Jun 26 16:31:52 -0700 2011
Processing by PollsController#update as JS
Parameters: {"poll"=>{"title"=>"Poll Options (2 only).3", "poll_options_attributes"=>{"0"=>{"title"=>"AAA", "id"=>"145"}, "1"=>{"title"=>"BBBB", "id"=>"146"}, "2"=>{"title"=>"", "id"=>"147"}}}, "commit"=>"Publish", "authenticity_token"=>"KaQrzinP3GNey9zN+sc0vAWU+VeUX1TRFSnQSscW7IA=", "utf8"=>"✓", "id"=>"50"}
控制器
@poll = Poll.new(:user_id => current_user)
3.times do
option = @poll.poll_options.build
end
表格
<%= form_for(@poll, :remote => true) do |f| %>
<%= f.text_field :title %>
<%= f.fields_for :poll_options do |f| %>
<%= f.text_field :title %>
<% end %>
<%= f.submit :class => '', :value => 'Publish' %>
<% end %>
知道我做错了什么吗?感谢
答案 0 :(得分:4)
在您的民意调查模型中尝试此操作。
accepts_nested_attributes_for :poll_options, :reject_if => lambda { |a| a[:title].blank? }, :allow_destroy => true
这个railscast很好地涵盖了嵌套模型:http://railscasts.com/episodes/196-nested-model-form-part-1