@@ -135,4 +135,84 @@ def test_find_by_key_with_customized_base_records
135135 def test_updateable_fields_does_not_include_id
136136 assert ( !CatResource . updateable_fields . include? ( :id ) )
137137 end
138+
139+ def test_has_many_association_filters
140+ post_resource = PostResource . new ( Post . find ( 1 ) )
141+ comments = post_resource . comments
142+ assert_equal ( 2 , comments . size )
143+
144+ # define apply_filters method on post resource to not respect filters
145+ PostResource . instance_eval do
146+ def apply_filters ( records , filters )
147+ records
148+ end
149+ end
150+
151+ filtered_comments = post_resource . comments ( { filters : { body : 'i liked it' } } )
152+ assert_equal ( 1 , filtered_comments . size )
153+
154+ # reset method to original implementation
155+ PostResource . instance_eval do
156+ def apply_filters ( records , filters )
157+ super
158+ end
159+ end
160+ end
161+
162+ def test_has_many_association_sorts
163+ post_resource = PostResource . new ( Post . find ( 1 ) )
164+ comment_ids = post_resource . comments . map { |c | c . model . id }
165+ assert_equal [ 1 , 2 ] , comment_ids
166+
167+ # define apply_filters method on post resource to not respect filters
168+ PostResource . instance_eval do
169+ def apply_sort ( records , criteria )
170+ records
171+ end
172+ end
173+
174+ sorted_comment_ids = post_resource . comments ( sort_criteria : [ { field : 'id' , direction : 'desc' } ] ) . map { |c | c . model . id }
175+ assert_equal [ 2 , 1 ] , sorted_comment_ids
176+
177+ # reset method to original implementation
178+ PostResource . instance_eval do
179+ def apply_sort ( records , criteria )
180+ super
181+ end
182+ end
183+ end
184+
185+ def test_has_many_association_pagination
186+ post_resource = PostResource . new ( Post . find ( 1 ) )
187+ comments = post_resource . comments
188+ assert_equal 2 , comments . size
189+
190+ # define apply_filters method on post resource to not respect filters
191+ PostResource . instance_eval do
192+ def apply_pagination ( records , criteria )
193+ records
194+ end
195+ end
196+
197+ paginator_class = Class . new ( JSONAPI ::Paginator ) do
198+ def initialize ( params )
199+ # param parsing and validation here
200+ @page = params . to_i
201+ end
202+
203+ def apply ( relation )
204+ relation . offset ( @page ) . limit ( 1 )
205+ end
206+ end
207+
208+ paged_comments = post_resource . comments ( paginator : paginator_class . new ( 1 ) )
209+ assert_equal 1 , paged_comments . size
210+
211+ # reset method to original implementation
212+ PostResource . instance_eval do
213+ def apply_pagination ( records , criteria )
214+ super
215+ end
216+ end
217+ end
138218end
0 commit comments