Why does ActiveRecord find_by return nil when using it together with select?

1.3k views Asked by At

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

There are 1 answers

0
Rosel Sosa Gonzalez On