2

次のモデルを定義すると...

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

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

2 回目の保存でも「更新」フックがトリガーされるのはなぜですか?

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

1 に答える 1

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より細かいレベルの制御が必要な場合はいつでも、フックを使用する必要があります。

于 2011-11-26T19:19:10.093 に答える