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 about 1 year 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 about 1 year ago

yep, this helps

Obie Fernandez about 1 year ago

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

Mike Nichols about 1 year ago

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

Obie Fernandez about 1 year 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 about 1 year ago