gpt4 book ai didi

ruby - :save hook relate to the :update hook in DataMapper?如何

转载 作者:数据小太阳 更新时间:2023-10-29 08:40:32 25 4
gpt4 key购买 nike

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

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

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

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

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

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

最佳答案

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 Hook ,并且 :create 和/或 :update 当你想要更好的控制级别时。

关于ruby - :save hook relate to the :update hook in DataMapper?如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7841457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com