JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources

has_one SQL not using LIMIT when using include

Open
#750 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Type: Bug
Dominant language
Ruby
Stars
2.3k
Forks
546
PR merge metrics
No merged PRs in 30d

Description

I have the following model:

class Foo < ActiveRecord::Base
  has_many :messages
  has_one :last_message, -> { order(created_at: :desc) }, class_name: 'Message'
end

and following resource:

class FooResource < JSONAPI::Resource
  has_one :last_message, class_name: 'Message'
end

When I request /foo/1/last-message it generates the following SQL:

SELECT  `messages`.* FROM `messages` WHERE `messages`.`foo_id` = 1  ORDER BY `messages`.`created_at` DESC LIMIT 1

But when I request /foo/1?include=last-message, the SQL doesnt append LIMIT

SELECT `messages`.* FROM `messages` WHERE `messages`.`foo_id` IN (1)  ORDER BY `messages`.`created_at` DESC

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the two requests shown in the issue and compare the generated SQL for the direct relationship and the included relationship. Trace the include-loading entry point to find where the has_one scope is applied, then verify that the included query preserves the single-record limit and ordering.

Written by the indexing model from the issue text.

Assessment

Tech stack
rails, ruby
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.