2011-10-20 3 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. 

をあなたが見ることができるようにあなたが何かは、A作成または更新のいずれかの後に起こる、と:createおよび/または:updateときなければならない時はいつでも:saveフックを使用したいと思いますより細かい制御が必要です。

+2

私はこのコードを使用して、一般的な前後のフックの素敵な図を生成しました:https://www.lucidchart.com/documents/view#4307-531c-4f1f159f-ace0-1ca90a7a4df5?branch=9cd86b38 -93fa-4432-ac0d-b351706819de – mltsy

+0

@mltsyフックが呼び出される前に、保存しているオブジェクトが汚れている必要があることを忘れないでください!それ以外の場合、フックはまったく動作しません。 – Frank

関連する問題