Hello everyone,
I ran into an issue while querying a has_one relationship recently, that kinda surprised me. Given these two simple models:
class Author < ApplicationRecord
has_one :biography
end
class Biography < ApplicationRecord
belongs_to :author
end
Specifying a condition on the has_one relationship using objects will work as intended:
Author.where(biography: Biography.all)
results in the SQL
SELECT "authors".* FROM "authors" WHERE "authors"."id" IN (SELECT "biographies"."author_id" FROM "biographies")
However, attempting the same query using an array of Biography IDs Author.where(biography: [1, 2])
results in this SQL:
SELECT "authors".* FROM "authors" WHERE "authors"."id" IN (1, 2)
Which is not what I would expect. I.e. it looks for authors that happen to have the same IDs as my biography IDs, not for authors with biographies having these IDs.
I’m now wondering whether this is actually a bug or intended/known behavior? In either case I think it should be changed and wanted to get some opinions on this before I create an issue in Github/attempt a patch. What made this result especially unexpected for me is, that doing this type of query on a belongs_to relationship actually works as expected, no matter how the condition is specified.