2011-06-26 43 views
1

我想要accept_nested_attributes_for,但它没有正确拒绝。这里有两种型号:accep_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民意调查的形式,但如果你填写2 3中, 3rd没有被删除。这里的日志:

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

更新与控制器和表单代码。 – AnApprentice

+0

需要更多的细节? – AnApprentice

回答

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

+0

这不正是我上面的吗? – AnApprentice

+0

它没有效果 – AnApprentice

+0

我刚刚注意到你显示的日志确实表示参数,但不是SQL。检查SQL以查看是否有任何内容被插入到poll_options中的空白标题字段中。 – moc