开发者

accepts_nested_attributes_for - How to reject empty nests?

开发者 https://www.devze.com 2023-03-15 18:23 出处:网络
I\'m trying 开发者_StackOverflowto accepts_nested_attributes_for but it isn\'t rejecting correctly. Here are the two models:

I'm trying 开发者_StackOverflowto accepts_nested_attributes_for but it isn't rejecting correctly. Here are the two models:

Poll

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

I build a poll form with 3 poll_options, but if you fill out 2 of the 3, the 3rd is not being deleted. Here's the log:

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

Controller

   @poll = Poll.new(:user_id => current_user)

    3.times do
      option = @poll.poll_options.build
    end

Form

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

Any idea what I'm doing wrong? Thanks


Try this in your Poll model.

accepts_nested_attributes_for :poll_options, :reject_if => lambda { |a| a[:title].blank? }, :allow_destroy => true

This railscast covers the nested model stuff pretty well: http://railscasts.com/episodes/196-nested-model-form-part-1

0

精彩评论

暂无评论...
验证码 换一张
取 消