2011-06-26 6 views
1

私はaccepts_nested_attributes_forを試みていますが、正しく拒否していません。ここでは、2つのモデルがあります:accepts_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

。 – 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ではなく、パラメータを示していることに気づいた。空白のタイトルフィールドのためにpoll_optionsに何かが挿入されているかどうかSQLを確認してください。 – moc

関連する問題