File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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
Original file line number Diff line number Diff line change @@ -18,11 +18,28 @@ def do_some_after_save_stuff
1818 end
1919end
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+
2130class ArticleWithBadAfterSaveResource < JSONAPI ::Resource
2231 model_name 'PostWithBadAfterSave'
2332 attribute :title
2433end
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+
2643class NoMatchResource < JSONAPI ::Resource
2744end
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
588614end
You can’t perform that action at this time.
0 commit comments