Skip to content

Add composite key support to `Model.exists?`

Created by: JoeDupuis

Fix #51295

.exists? does not support composite primary key because it would clash with the current expectation when passing an array.

This PR would make it possible to pass a composite primary key by wrapping it in an array:

CpkModel.exists?([[1,1]]) # as in `CpkModel.exists?([composite_primary_key])`

Incidentally, it would also allow searching with multiple keys without having to use the hash form:

CpkModel.exists?([[1,1], [1,2], [3,1]])  
RegularModel.exists?([[1,2,3]]) # Even works for non regular models! Generates: `SELECT 1 AS one FROM "regular_models" WHERE "users"."id" IN (1, 2, 3)`

Considerations

This is a bit of hack and initially thought of answering #51295 by suggesting using the hash form instead, but after looking at what the hash form would look like for a primary key:

CpkModel.exists?(CpkModel.primary_key => [[1,1]]) # You need to wrap the primary key in an array!

This is quite verbose. So perhaps there is value in this. I did not edit the documentation and changelog yet. Only the code, plus a couple tests. If this diff is deemed valuable I'll add the required edits.

Checklist

Before submitting the PR make sure the following are checked:

  • This Pull Request is related to one change. Changes that are unrelated should be opened in separate PRs.
  • Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
  • Tests are added or updated if you fix a bug or add a feature.
  • CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.

Merge request reports