我有一個使用叉的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