Juny
Juny

Reputation: 299

How to get users that was created on specific day of week on ruby?

i'm trying to create some kpi's on ruby on rails.

How can i count all users that was created on sunday or on wednesday for example?

I now that ruby can get day of week with the follow code for example:

u = User.last
u.created_at.wday #==> wday get the day of week (0: sunday, 1: monday..)

But the following doesn't work:

User.where(created_at.wday: 0).count

And I don't want to loop each user, check if it was created on sunday and put it in an array, because it seems to be costly.

Any ideas?

Upvotes: 1

Views: 102

Answers (1)

Joel Blum
Joel Blum

Reputation: 7878

If you're using MYSQL you can use dayofweek

User.where('DAYOFWEEK(created_at) = ?', 0).count

For Postgres this should do the trick:

User.where("extract(dow from created_at) = ?", 0)

EDIT: For SQLITE the following works:

User.where("strftime('%w', created_at) = ?", 0)

Upvotes: 4

Related Questions