I found the following kind of usage of ActiveRecord#find_by written in a Rails 4.1 project:
booking = Booking.find_by(member_id: Member.where(id: 1).select(:id))
However, this query returned nil after upgrading the project to Rails > 4.2.
In Rails 4.2 the above query generates the following SQL:
SELECT "bookings".* FROM "bookings" WHERE "bookings"."member_id" = $1 LIMIT 1 [["member_id", nil]]
A 'Booking' belongs to a 'Member' and a 'Member' has many 'Booking'.
Does anyone know or see why? I would be interested in an explanation.
Replacing the select with pluck brings back the expected behavior:
booking = Booking.find_by(member_id: Member.where(id: 1).pluck(:id))
Generated query: SELECT "bookings".* FROM "bookings" WHERE "bookings"."member_id" = 1 LIMIT 1
Edit: A member record with ID 1 exists in the database.
Member.where(id: 1).select(:id)
returns the following result and SQL statement with Rails 4.2:
=> #<ActiveRecord::Relation [#<Member id: 1>]>
SELECT "members"."id" FROM "members" WHERE "members"."id" = $1 [["id", 1]]
where
andfind_by
and now I cannot reproduce it anymore. Are you sure the last edit is correct? theMember.find_by(id: 1).select(:id)
returns nil always. The current form should just work, albeit being very inefficient (if you have the member-id, just use it immediately instead of retrieving all the members with that id, and selecting their id). – nathanvdaMember.where(id: 1).select(:id)
does return a ActiveRecord::Relation but combined withBooking.find_by(member_id: Member.where(id: 1).select(:id))
the result is nil in Rails > 4.2 and that's my question. – Jelan.find_by(member_id: Member.where(id: 1).select(:id))
I getnil
. I do not understand since the implementation offind_by
is justwhere(*args).take
. If I usewhere(..).first
orwhere(...).take
it just works, but writingfind_by
with the same arguments invariably returns nil? Mmmmm interesting ... – nathanvda