stas / jsonapi.rb

Lightweight, simple and maintained JSON:API support for your next Ruby HTTP API.
MIT License
262 stars 58 forks source link

Fix where grouped resources will return a hash which causing error #61

Closed khrisnagunanasurya-iav closed 3 years ago

khrisnagunanasurya-iav commented 3 years ago

What is the current behavior?

Fix https://github.com/stas/jsonapi.rb/issues/60, where on grouped resources jsonapi_pagination_meta will trigger an error, because .size on grouped resources will return a hash

What is the new behavior?

Replace .size to .length which will always return integer

Checklist

Please make sure the following requirements are complete:

stas commented 3 years ago

@khrisnagunanasurya-iav I'm not sure I follow completely what's the issue here, #size is the safest method to call on a collection of records, consider this explanation: https://medium.com/@mingca/activerecord-count-vs-length-vs-size-and-what-will-happen-if-you-use-it-the-way-you-shouldnt-2256ec0ab7e8

In #60 you're running a custom query that overwrites the calls generated from #size. Generally, I'm not sure what you're trying to achieve there, it looks like you're trying to count the user-related notes in the same query, please consider looking into counter cashes for that reason: https://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-counter-cache

I'll be closing this, since you're definitely doing something in-house and I see no reasons to support non-standard SQL calls. As a quick fix for your problem, consider wrapping the query in a Array() call:

(rdb:1) Array(User.left_joins(:notes).select('users.*, COUNT(notes.id) AS note_counts').group('users.id')).size
3