accepts_nested_attributes_for&:reject_if.在父母协会保存之前如何防止拒绝?

Gav*_*vin 7 ruby-on-rails

class Gift < ActiveRecord::Base
  has_many :contributions
  accepts_nested_attributes_for :contributions, :reject_if => proc { |a| a['amount'].blank? }
Run Code Online (Sandbox Code Playgroud)

贡献有:nickname属性.在:新表单中,它预先填充了用户的真实姓名.用户可能决定将其更改为"Uncle Bob"(或其他).不幸的是,使用:reject_if,如果贡献中没有指定金额,则:在以下情况下,昵称更改将丢失:在@gift无效的情况下重新加载.发生这种情况是因为嵌套的contrib_attributes被拒绝.我们如何保留:昵称更改并仅在实际保存@gift时处理拒绝?

Gav*_*vin 9

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
Run Code Online (Sandbox Code Playgroud)

......礼物形式......

f.text_field :nickname, :value => (params[:gift][:contributions_attributes]['0'][:nickname] rescue @m.full_name)
Run Code Online (Sandbox Code Playgroud)

这会保留:昵称通过失败的验证进行更改,但仍会丢弃包含以下内容的嵌套式贡献:仅限昵称.