我有一个使用叉的acts_as_nested_set
模型,并且我在模型中添加了一个方法来保存模型并将节点移动到一个事务中的集合中。此方法调用验证方法以确保移动有效,并返回true或false。如果验证失败,我希望使用我的保存方法提高ActiveRecord::Rollback
以回滚事务,但也会将错误返回给调用者。如何引发ActiveRecord :: Rollback异常并返回一个值?
我的模型看起来是这样的:
class Category < ActiveRecord::Base
acts_as_nested_set :dependent => :destroy, :scope => :journal
def save_with_place_in_set(parent_id)
Category.transaction do
return false if !save_without_place_in_set
if !validate_move parent_id
raise ActiveRecord::Rollback and return false
else
place_in_nested_set parent_id
return true
end
end
end
alias_method_chain :save, :place_in_set
def validate_move(parent_id)
# return true or false if the move is valid
# ...
end
def place_in_nested_set(parent_id)
# place the node in the correct place in the set
# ...
end
end
然而,当我打电话保存在会失败的情况下,该事务回滚,但该函数返回nil
:
>> c = Category.new(:name => "test")
=> #<Category id: nil, name: "test" parent_id: nil, lft: nil, rgt: nil>
>> c.save_with_place_in_set 47
=> nil
>> c.errors.full_messages
=> ["The specified parent is invalid"]
+1,我得出的结论基本相同。 – 2009-06-29 15:24:27