Skip to content

Instantly share code, notes, and snippets.

@beccasaurus
Created February 3, 2010 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beccasaurus/42aae62a079fa6cab643 to your computer and use it in GitHub Desktop.
Save beccasaurus/42aae62a079fa6cab643 to your computer and use it in GitHub Desktop.
#save but still dirty
update_dog_most_recently_chewed_toy
Toy: #<Toy @id=1 @name="Squeeky Toy" @dog_id=1>
Dog: #<Dog @id=1 @name="Rover" @most_recently_chewed_toy_id=nil>
dog.dirty_attributes: {#<DataMapper::Property @model=Dog @name=:most_recently_chewed_toy_id>=>1}
dog.save: true
dog.dirty_attributes: {#<DataMapper::Property @model=Dog @name=:most_recently_chewed_toy_id>=>1}
[before reload] dog.most_recently_chewed_toy = #<Toy @id=1 @name="Squeeky Toy" @dog_id=1>
[after reload] dog.most_recently_chewed_toy = nil
- should work (FAILED - 1)
1)
NoMethodError in '#save but still dirty should work'
undefined method `name' for nil:NilClass
./save-but-still-dirty_spec.rb:68:
Finished in 0.019621 seconds
1 example, 1 failure
%w( rubygems dm-core dm-validations dm-timestamps dm-aggregates ).each {|lib| require lib }
class Dog
include DataMapper::Resource
property :id, Serial
property :name, String
belongs_to :most_recently_chewed_toy, :model => 'Toy', :required => false
has n, :toys
end
class Toy
include DataMapper::Resource
property :id, Serial
property :name, String
belongs_to :dog
after :save, :update_dog_most_recently_chewed_toy
private
def update_dog_most_recently_chewed_toy
puts "\nupdate_dog_most_recently_chewed_toy"
puts " Toy: #{ inspect }"
puts " Dog: #{ dog.inspect }\n\n"
dog.most_recently_chewed_toy = dog.toys.last
puts "dog.dirty_attributes: #{ dog.dirty_attributes.inspect }"
puts "dog.save: #{ dog.save }"
puts "dog.dirty_attributes: #{ dog.dirty_attributes.inspect }"
# double check that we actually set it properly
puts "\n[before reload] dog.most_recently_chewed_toy = #{ dog.most_recently_chewed_toy.inspect }"
dog.reload
puts "[after reload] dog.most_recently_chewed_toy = #{ dog.most_recently_chewed_toy.inspect }"
end
end
DataMapper.setup :default, 'sqlite3::memory:'
DataMapper.auto_migrate!
describe '#save but still dirty' do
it 'should work' do
# There is 1 Dog and 0 Toys
dog = Dog.create :name => 'Rover'
Toy.count.should == 0
Dog.count.should == 1
# We create a new Toy for this Dog
dog.toys.new :name => 'Squeeky Toy'
dog.save
# We double check that the Toy was created properly
Toy.count.should == 1
toy = Toy.first
toy.should_not be_new
toy.name.should == 'Squeeky Toy'
toy.dog.should == dog
# We make sure that the dog's #most_recently_chewed_toy was set
dog.reload
dog.most_recently_chewed_toy.name.should == 'Squeeky Toy' # <--- BOOM!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment