2011-10-20 36 views
2

如果我定義如下模型...:save鉤子與DataMapper中的update鉤子有什麼關係?

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 

當然,我可以潛入源代碼並回答代碼驅動這種行爲的問題。更重要的是,我想要理解在實踐中使用每個鉤子的正確方法。

回答

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當你想要更好的控制水平。

+2

我已經使用這段代碼來幫助我生成一個很好的鉤子前後公共圖:https://www.lucidchart.com/documents/view#4307-531c-4f1f159f-ace0-1ca90a7a4df5?branch=9cd86b38 -93fa-4432-ac0d-b351706819de – mltsy

+0

@mltsy不要忘記在調用鉤子之前,你保存的對象必須是髒的!否則,掛鉤根本不運行。 – Frank