提交 328ba3b3 编写于 作者: T taryn 提交者: Joshua Peek

Added save! which raises ResourceInvalid unless valid?

Similar to Active Record - it will raise ActiveResouce::ResourceInvalid if
the resource is not valid (ie if <tt>valid?</tt> returns false)

However - does not raise ActiveResource::ResourceNotFound if the callbacks
fail (callbacks have not yet been implemented) - it will just try to save
and raise if the callbacks all fail.

This is not ideal behaviour - but will do until we decide to change the
behaviour of save_with_validations to actually raise (rather than catch) the
ResourceInvalid exception.
Signed-off-by: NJoshua Peek <josh@joshpeek.com>
上级 4dc05bc8
...@@ -893,6 +893,23 @@ def dup ...@@ -893,6 +893,23 @@ def dup
def save def save
new? ? create : update new? ? create : update
end end
# Saves the resource.
#
# If the resource is new, it is created via +POST+, otherwise the
# existing resource is updated via +PUT+.
#
# With <tt>save!</tt> validations always run. If any of them fail
# ActiveResource::ResourceInvalid gets raised, and nothing is POSTed to
# the remote system.
# See ActiveResource::Validations for more information.
#
# There's a series of callbacks associated with <tt>save!</tt>. If any
# of the <tt>before_*</tt> callbacks return +false+ the action is
# cancelled and <tt>save!</tt> raises ActiveResource::ResourceInvalid.
def save!
save || raise(ResourceInvalid.new(self))
end
# Deletes the resource from the remote service. # Deletes the resource from the remote service.
# #
......
...@@ -654,7 +654,13 @@ def test_custom_header ...@@ -654,7 +654,13 @@ def test_custom_header
def test_save def test_save
rick = Person.new rick = Person.new
assert_equal true, rick.save assert rick.save
assert_equal '5', rick.id
end
def test_save!
rick = Person.new
assert rick.save!
assert_equal '5', rick.id assert_equal '5', rick.id
end end
......
...@@ -23,9 +23,15 @@ def test_validates_presence_of ...@@ -23,9 +23,15 @@ def test_validates_presence_of
assert p.save, "should have saved after fixing the validation, but had: #{p.errors.inspect}" assert p.save, "should have saved after fixing the validation, but had: #{p.errors.inspect}"
end end
def test_fails_save!
p = new_project(:name => nil)
assert_raise(ActiveResource::ResourceInvalid) { p.save! }
end
def test_validate_callback def test_validate_callback
# we have a callback ensuring the description is longer thn three letters # we have a callback ensuring the description is longer than three letters
p = new_project(:description => 'a') p = new_project(:description => 'a')
assert !p.valid?, "should not be a valid record when it fails a validation callback" assert !p.valid?, "should not be a valid record when it fails a validation callback"
assert !p.save, "should not have saved an invalid record" assert !p.save, "should not have saved an invalid record"
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册