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 @@ -406,7 +406,7 @@ def destroy
406406 $breed_data. remove ( @id )
407407 end
408408
409- def valid?
409+ def valid? ( context = nil )
410410 @errors . clear
411411 if name . is_a? ( String ) && name . length > 0
412412 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
@@ -557,4 +574,13 @@ def test_resource_for_model_use_hint
557574 resource_model = SpecialPersonResource . records ( { } ) . first # simulate a find
558575 assert_equal ( SpecialPersonResource , SpecialPersonResource . resource_for_model ( resource_model ) )
559576 end
577+
578+ def test_resource_performs_validations_in_custom_context
579+ post = PostWithCustomValidationContext . find ( 1 )
580+ post_resource = ArticleWithCustomValidationContextResource . new ( post , nil )
581+ err = assert_raises JSONAPI ::Exceptions ::ValidationErrors do
582+ post_resource . _save
583+ end
584+ assert_equal ( err . error_messages [ :base ] , [ 'Record is invalid' ] )
585+ end
560586end
You can’t perform that action at this time.
0 commit comments