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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With