Many people link to .pluck . He has a caution, he returns an array of columns for the found records.
If the column is unique, such as id , this is not a problem, the database will send the same content to Active Record, 1 record 1 column using limit(1) or not. Its use is useless, and most likely it will be rejected by the database query optimizer.
But if the column is not unique, this could be a more serious problem. first is called after AR executes a query on the database, returning [0] results obtained from the database. limit , called earlier and sent to the database as part of the request.
Consider the following table and configuration:
> Log => Log(id: integer, user_id, integer, event_type: integer, timestamp: datetime) > user_newest_logs = Log.where(user_id: 1).order(timestamp: :desc)
Now let's get the date time of the last event for user_id = 1:
1) this is the best way
> user_newest_logs.limit(1).pluck(:timestamp).first SELECT timestamp FROM logs WHERE logs.user_id = 1 ORDER BY logs.timestamp DESC LIMIT 1 => Fri, 09 Aug 2019 23:00:00 UTC +00:00
2) both get the same data from the database
> user_newest_logs.first SELECT * FROM logs WHERE logs.user_id = 1 ORDER BY logs.timestamp DESC LIMIT 1 => #<Log:0x00111111> id: 920821839, user_id: 1, event_type: 1, timestamp: Fri, 09 Aug 2019 23:00:00 UTC +00:00 > user_newest_logs.first.timestamp SELECT * FROM logs WHERE logs.user_id = 1 ORDER BY logs.timestamp DESC LIMIT 1 => Fri, 09 Aug 2019 23:00:00 UTC +00:00
3) everyone extracts the same data from the database
> user_newest_logs.pluck(:timestamp) SELECT timestamp FROM logs WHERE logs.user_id = 1 ORDER BY logs.timestamp DESC => [Fri, 09 Aug 2019 23:00:00 UTC +00:00, Fri, 09 Aug 2019 22:00:00 UTC +00:00, Fri, 09 Aug 2019 21:00:00 UTC +00:00, Fri, 09 Aug 2019 20:00:00 UTC +00:00, ... ] > user_newest_logs.pluck(:timestamp).first SELECT timestamp FROM logs WHERE logs.user_id = 1 ORDER BY logs.timestamp DESC => Fri, 09 Aug 2019 23:00:00 UTC +00:00 > user_newest_logs.pluck(:timestamp).count
So, if you do, pluck(:column).first may actually be worse than just find_by.column .