cerebris / jsonapi-resources

A resource-focused Rails library for developing JSON:API compliant servers.
http://jsonapi-resources.com
MIT License
2.32k stars 529 forks source link

sort by country that is related to resource not directly but through the third relation is not work properly #1409

Open Ivanov-Anton opened 1 year ago

Ivanov-Anton commented 1 year ago

This issue is a (choose one):

Checklist before submitting:

Description

When making a request to a specific API endpoint with the query parameter sort=country.name, the application crashes due to an error in the sorting mechanism. The problem arises because the country relationship does not directly belong to the destination model but rather through another association. This leads to an undefined column error when attempting to perform the sorting operation.

Additional info

class Routing::Destination < ApplicationRecord
  belongs_to :network_prefix, class_name: 'System::NetworkPrefix', optional: true
  has_one :country, through: :network_prefix
end

class Api::Rest::Admin::Routing::DestinationResource < JSONAPI::Resource
  has_one :country, class_name: 'Country', force_routed: true, foreign_key_on: :related
end

class System::NetworkPrefix < ApplicationRecord
  belongs_to :country, class_name: 'System::Country', foreign_key: :country_id, optional: true
end
request that lead to 500 error
GET /destinations?sort=country.name
SELECT "class4"."destinations".* FROM "class4"."destinations"
LEFT JOIN sys.countries AS country_sorting ON country_sorting.id = class4.destinations.country_id
LEFT JOIN class4.rate_groups AS rate_group_sorting ON rate_group_sorting.id = class4.destinations.rate_group_id
ORDER BY country_sorting.name asc, rate_group_sorting.name asc LIMIT $1 OFFSET $2  [["LIMIT", 50], ["OFFSET", 0]]

Internal Server Error: PG::UndefinedColumn: ERROR:  column destinations.country_id does not exist
LINE 1: ...ntries AS country_sorting ON country_sorting.id = class4.des...
                                                             ^

jsonapi-resource version 0.9.12

johnnymo87 commented 1 year ago

In the 0.9 version of the gem, the sorting on relationships _only works for belongs_to relationships_. I believe this is the actual bug here.

Ivanov-Anton commented 1 year ago

@johnnymo87 Yeah correct. I'll try to improve this method to fix this in release-0-9 branch

baranyeni commented 1 year ago

As a workaround I plucked the ids from the query results and generated another query like this Model.where(id: ids) by so, sorting is possible since there are no relations etc. and it works even I don't like how it performs