如何:save钩子与DataMapper中的:update钩子有关?

时间:2011-10-20 19:53:10

标签: ruby hook ruby-datamapper

如果我定义以下模型......

class Foo
  include DataMapper::Resource
  property :name, String, :key => true

  before :save,  do
    puts 'save'
  end
  before :update,  do
    puts 'update'
  end
end

为什么第二次保存也会触发“更新”钩子?

ruby :001 > f = Foo.new
 => #<Foo @name=nil> 
ruby :002 > f.name = 'Bob'
 => "Bob" 
ruby :003 > f.save
save
 => true 
ruby :004 > f.name = 'Joe'
 => "Joe" 
ruby :005 > f.save
save
update
 => true 

当然,我可以深入了解源代码并回答代码驱动此行为的问题。更重要的是,我想了解在实践中使用这些钩子的正确方法。

1 个答案:

答案 0 :(得分:4)

require 'rubygems'
require 'data_mapper'

class Foo
  include DataMapper::Resource

  property :name, String, :key => true

  before :create,  do
    puts 'Create: Only happens when saving a new object.'
  end

  before :update,  do
    puts 'Update: Only happens when saving an existing object.'
  end

  before :save,  do
    puts 'Save: Happens when either creating or updating an object.'
  end

  before :destroy,  do
    puts 'Destroy: Only happens when destroying an existing object.'
  end
end

DataMapper.setup :default, 'sqlite::memory:'
DataMapper.finalize
DataMapper.auto_migrate!

puts "New Foo:"
f = Foo.new :name => "Fighter"
f.save

puts "\nUpdate Foo:"
f.name = "Bar"
f.save

puts "\nUpdate Foo again:"
f.update :name => "Baz"

puts "\nDestroy Foo:"
f.destroy

返回:

New Foo:
Save: Happens when either creating or updating an object.
Create: Only happens when saving a new object.

Update Foo:
Save: Happens when either creating or updating an object.
Update: Only happens when saving an existing object.

Update Foo again:
Save: Happens when either creating or updating an object.
Update: Only happens when saving an existing object.

Destroy Foo:
Destroy: Only happens when destroying an existing object.

因为你可以看到你想在创建或更新之后发生某些事情时使用:save钩子,并且当你想要一个:create和/或:update时更好的控制水平。