Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Attributes: unwanted validation despite of reject_if : All_blank

I am new to rails so any advise is greatly appreciated.

I have a class Entry with nested attributes Addresses,

/app/models/entry.rb

class Entry < ActiveRecord::Base
  has_many :addresses, :dependent => :destroy
  accepts_nested_attributes_for :addresses,
                                :allow_destroy => true,
                                :reject_if => :all_blank
end

with class Addresses like this

/app/models/address.rb

class Address < ActiveRecord::Base
  belongs_to :entry
  validates :zip, :presence => true
end

And in the nested form I have

/app/view/entries/_form.html.slim

= simple_form_for(@entry) do |f|
  = f.error_notification
  - @entry.addresses.build
  .form-inputs
    = f.simple_fields_for :addresses do |address|
      = render 'address_form', :f => address

The idea is that when the form is rendered, the 'build' will create a empty 'address' in addition to the current addresses listed in database. When the changes are saved, if the new address created is still empty, it will get rejected and not saved to the database.

However the validation in the address.rb is doing the validation before the saving, hence the user cannot proceed with the saving action. Is there anything I left out?

like image 512
James Liu Avatar asked Apr 08 '13 21:04

James Liu


1 Answers

You might like to try explicitly naming the attributes in your address model that get checked before a new, empty one is created. Something like this:

# in app/models/entry.rb

accepts_nested_attributes_for :addresses, reject_if: lambda {|attributes| nested_address_is_empty?(attributes) }

private

def self.nested_address_is_empty?(attrs)
  attrs['line_1'].blank? && attrs['line_2'].blank? && attrs['zip'].blank?
end
like image 84
Dan Laffan Avatar answered Nov 08 '22 06:11

Dan Laffan