Skip to content

Commit 2a7e1b1

Browse files
committed
Merge pull request #665 from lessless/master
Add ability to specify validation context
2 parents 5a68312 + f0caa54 commit 2a7e1b1

3 files changed

Lines changed: 29 additions & 3 deletions

File tree

lib/jsonapi/resource.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ def save
182182
# return :accepted
183183
# end
184184
# ```
185-
def _save
186-
unless @model.valid?
185+
def _save(validation_context = nil)
186+
unless @model.valid?(validation_context)
187187
fail JSONAPI::Exceptions::ValidationErrors.new(self)
188188
end
189189

test/fixtures/active_record.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -419,7 +419,7 @@ def destroy
419419
$breed_data.remove(@id)
420420
end
421421

422-
def valid?
422+
def valid?(context = nil)
423423
@errors.clear
424424
if name.is_a?(String) && name.length > 0
425425
return true

test/unit/resource/resource_test.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,28 @@ def do_some_after_save_stuff
1818
end
1919
end
2020

21+
class PostWithCustomValidationContext < ActiveRecord::Base
22+
self.table_name = 'posts'
23+
validate :api_specific_check, on: :json_api_create
24+
25+
def api_specific_check
26+
errors[:base] << 'Record is invalid'
27+
end
28+
end
29+
2130
class ArticleWithBadAfterSaveResource < JSONAPI::Resource
2231
model_name 'PostWithBadAfterSave'
2332
attribute :title
2433
end
2534

35+
class ArticleWithCustomValidationContextResource < JSONAPI::Resource
36+
model_name 'PostWithCustomValidationContext'
37+
attribute :title
38+
def _save
39+
super(:json_api_create)
40+
end
41+
end
42+
2643
class NoMatchResource < JSONAPI::Resource
2744
end
2845

@@ -585,4 +602,13 @@ def test_resource_for_model_use_hint
585602
resource_model = SpecialPersonResource.records({}).first # simulate a find
586603
assert_equal(SpecialPersonResource, SpecialPersonResource.resource_for_model(resource_model))
587604
end
605+
606+
def test_resource_performs_validations_in_custom_context
607+
post = PostWithCustomValidationContext.find(1)
608+
post_resource = ArticleWithCustomValidationContextResource.new(post, nil)
609+
err = assert_raises JSONAPI::Exceptions::ValidationErrors do
610+
post_resource._save
611+
end
612+
assert_equal(err.error_messages[:base], ['Record is invalid'])
613+
end
588614
end

0 commit comments

Comments
 (0)