2011-06-26 92 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