简体   繁体   English

为什么ActiveRecord find_by与select一起使用时返回nil?

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

I found the following kind of usage of ActiveRecord#find_by written in a Rails 4.1 project:我在 Rails 4.1 项目中发现了 ActiveRecord#find_by 的以下用法:

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.但是,在将项目升级到 Rails > 4.2 后,此查询返回 nil。

In Rails 4.2 the above query generates the following SQL:在 Rails 4.2 中,上述查询生成以下 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'.一个“Booking”属于一个“Member”,一个“Member”有多个“Booking”。

Does anyone know or see why?有谁知道或明白为什么? I would be interested in an explanation.我会对解释感兴趣。

Replacing the select with pluck brings back the expected behavior:用 pluck 替换 select 会恢复预期的行为:

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生成的查询: SELECT "bookings".* FROM "bookings" WHERE "bookings"."member_id" = 1 LIMIT 1

Edit: A member record with ID 1 exists in the database.编辑:数据库中存在 ID 为 1 的成员记录。

Member.where(id: 1).select(:id) returns the following result and SQL statement with Rails 4.2: Member.where(id: 1).select(:id)使用 Rails 4.2 返回以下结果和 SQL 语句:

=> #<ActiveRecord::Relation [#<Member id: 1>]>

SELECT "members"."id" FROM "members" WHERE "members"."id" = $1 [["id", 1]]

Because is the default behavior of find_by :因为是find_by的默认行为:

Finds the first record matching the specified conditions.查找与指定条件匹配的第一条记录。 There is no implied ordering so if order matters, you should specify it yourself.没有隐含的顺序,所以如果顺序很重要,您应该自己指定。

If no record is found, returns nil.如果没有找到记录,则返回 nil。

The SQL produced shows the result of Member.where(id: 1).select(:id) is converted to nil at the moment of executing the query.生成的 SQL 显示Member.where(id: 1).select(:id)的结果在执行查询时被转换为 nil。 Which is the case of being an empty array - denoting there are no members with id = 1 .这是一个空数组的情况 - 表示没有id = 1的成员。


Note if you have the member ids you don't need to query them (again).请注意,如果您有成员 ID,则不需要(再次)查询它们。 It's supposed a book should have a member_id column, which allows you to do:假设一本书应该有一个 member_id 列,它允许您执行以下操作:

Book.where(member_id: <member_ids>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM