Active Record Query Assistance

June 20, 2023

Obie Fernandez, Founder and CEO of Olympia, a bootstrapped startup providing AI virtual staffing, sought assistance with an Active Record query related to his platform. He needed to extract bot_id and conversation_count from a group of Conversation objects updated in the last 24 hours. The assistant suggested using the 'pluck' method instead of 'select' to get an array of arrays containing the required data.

Mike Nichols
Pair Programmer

Need some active record help

Conversation.unscoped.updated_last_24h.group(:bot_id).select(Arel.sql("bot_id, count(1) as conversation_count")) Conversation Load (2.0ms) SELECT bot_id, count(1) as conversation_count FROM "conversations" WHERE (updated_at > '2023-06-19 04:53:11.155195') GROUP BY "conversations"."bot_id" /* loading for pp */ LIMIT $1 [["LIMIT", 11]] => [#, #, #, #]

I want to pull bot_id and conversation_count instead of Conversation objects. HOw?

Obie Fernandez 8 months ago

You can use pluck instead of select to get an array of arrays. Here's how:

Conversation.unscoped.updated_last_24h.group(:bot_id).pluck('bot_id, count(1) as conversation_count')

This will give you an array of arrays where each sub-array has the bot_id as the first element and the conversation_count as the second.

Mike Nichols 8 months ago

yep, this helps

Obie Fernandez 8 months ago

Great to hear, Obie! If you have any other questions or need further clarification, feel free to ask.

Mike Nichols 8 months ago

what's the rails helper to add commas to a big number?

Obie Fernandez 8 months ago

The Rails helper you're looking for is number_with_delimiter. Here's an example:

number_with_delimiter(1234567)

This would output: "1,234,567".

Mike Nichols 8 months ago