1
votes

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]]

1
Mmmmm you switched the position of where and find_by and now I cannot reproduce it anymore. Are you sure the last edit is correct? the Member.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).nathanvda
Thanks nathanvda for your comment. I only edited the last part of the question starting from "Edit:". Member.where(id: 1).select(:id) does return a ActiveRecord::Relation but combined with Booking.find_by(member_id: Member.where(id: 1).select(:id)) the result is nil in Rails > 4.2 and that's my question.Jelan
Ah ok, must have misread then. I see it now, I can reproduce it as well. If I write .find_by(member_id: Member.where(id: 1).select(:id)) I get nil. I do not understand since the implementation of find_by is just where(*args).take. If I use where(..).first or where(...).take it just works, but writing find_by with the same arguments invariably returns nil? Mmmmm interesting ...nathanvda
I have the exact same findings, nathanvda. Mhhhh...Jelan

1 Answers