Q:

accepts_nested_attributes_for & :reject_if. How to prevent rejection until parent association saves?

class Gift < ActiveRecord::Base
  has_many :contributions
  accepts_nested_attributes_for :contributions, :reject_if => proc { |a| a['amount'].blank? }

Contribution has a :nickname attribute. In the :new form, it is pre-populated with the user's real name. A user might decide to change it to "Uncle Bob" (or whatever).  Unfortunately, with :reject_if, if no amount is specified in the contribution, the :nickname change is lost when :new reloads in cases where @gift is not valid.  This happens because the nested contribution_attributes are rejected.  How do we preserve the :nickname change and only handle the rejection when @gift is actually saved?

A:

class Gift < ActiveRecord::Base
  has_many :contributions
  accepts_nested_attributes_for :contributions,
    :reject_if => proc { |a| a['amount'].blank? }
end

class Contribution < ActiveRecord::Base
  belongs_to :gift
  validates_presence_of :nickname, :amount
end

...in the gift form...
f.text_field :nickname, :value => (params[:gift][:contributions_attributes]['0'][:nickname] rescue @m.full_name)

This preserves :nickname changes through failed validations and still discards a nested contributions that contain :nickname only.

