1
DataMapper에서 콜백을 정의하고이 업데이트를 동반 한 업데이트와 함께 트랜잭션에서 수행 할 수 있기를 바랍니다. 예를 들어하십시오 Comment
가 업데이트 될 때마다, 또한 해당 Update
레코드를 만들 :트랜잭션에서 DataMapper 콜백을 어떻게 처리합니까?
class Comment
include DataMapper::Resource
has n, :updates
property :id, Serial
property :text, String
after :update do
self.updates.create(:text => self.text)
end
end
나는 위의 코드가 시도되고 분명한 생각합니다. 가능한 시나리오는 게시를 업데이트 할 수 있으며 어떤 이유로 든 업데이트를 만들지 못하게되므로 일부 기록이 손실 될 수 있다는 것입니다. 그래서 저는 이런 종류의 작업이 트랜잭션 내에서 발생하기를 정말로 원합니다.
이것이 가능합니까? 몇 가지 해결 방법을 생각해 볼 수 있습니다 (예 : 사용자 정의 update
메소드 정의). 그러나 나는 "올바른"방법이 있는지 또는 다른 사람들이 우아한 접근 방식을 생각할 수 있는지 알고 싶어합니다. 이 답변에 동의하지
class CommentUpdate
private_class_method :new
# Run comment update within transaction
def self.run(*args)
Comment.transaction do
new(*args)
end
end
# Initialize object
#
# @param [Comment]
# the comment to update
# @param [String]
# the text to set
#
def initialize(comment, text)
@comment, @text = comment, text
run
end
# Test if update was successful
def successful?
@comment.saved?
end
private
# Run update
def run
@comment.text = @text
if @comment.save
@comment.updates.create(:text => @text)
end
end
end
# usage
comment = Comment.first
update = CommentUpdate.run(comment, "Some new cool text")
update.successful? # Use this to steer your control flow...
어떤 이유 : – mbj