Permalink
Browse files

Add nested attibutes for shipping_addresses

  • Loading branch information...
1 parent f2a09ad commit 8c928ba9158a0c6d554364fe3747ba8ec040d17b @wolframarnold wolframarnold committed Mar 21, 2011
Showing with 32 additions and 1 deletion.
  1. +3 −1 app/models/user.rb
  2. +29 −0 spec/models/user_spec.rb
View
@@ -3,10 +3,12 @@ class User < ActiveRecord::Base
validates :first_name, :last_name, :presence => true
validates :email, :email => {:message => "is not a valid email address"}, :allow_blank => true
- attr_accessible :first_name, :middle_name, :last_name, :email
+ attr_accessible :first_name, :middle_name, :last_name, :email, :shipping_addresses_attributes
has_many :shipping_addresses, :dependent => :destroy
+ accepts_nested_attributes_for :shipping_addresses, :reject_if => :all_blank, :allow_destroy => true
+
def full_name
name = first_name
name << (' ' + middle_name) unless middle_name.blank?
@@ -57,6 +57,35 @@
subject.shipping_addresses.create(:street => "123 Main St", :city => "San Francisco", :state => "CA", :zip => "94321")
}.to change(ShippingAddress,:count).by(1)
end
+
+ context "nested attributes" do
+ subject { Factory(:user) }
+
+ it 'can be updated via nested attributes' do
+ lambda {
+ subject.attributes = {:shipping_addresses_attributes => [Factory.attributes_for(:shipping_address)]}
+ subject.save!
+ puts subject.errors
+ }.should change {subject.shipping_addresses.count}.by(1)
+ end
+
+ it "won't add a shipping address if all fields are blank" do
+ lambda {
+ subject.attributes = {:shipping_addresses_attributes => [:street => '', :city => '', :state => '', :zip =>'']}
+ subject.save!
+ }.should_not change {subject.shipping_addresses.count}
+ end
+
+ it 'can delete an address via nested attributes and _destroy flag' do
+ addr = subject.shipping_addresses.create(Factory.attributes_for(:shipping_address))
+ lambda {
+ subject.attributes = {:shipping_addresses_attributes => [{:id => addr.id, :_destroy => 1}]}
+ subject.save!
+ }.should change{subject.shipping_addresses.count}.by(-1) # addresses(true) causes a reload
+ end
+
+ end
+
end
end

0 comments on commit 8c928ba

Please sign in to comment.