How would you program "You have posted 5 days in a row..."?

If you want to show the number of consecutive days a user has posted (e.g. "You have posted 5 days in a row"), how would you do it?

I have no idea how to do this. I'm guessing it's something along the lines of current_user.posts.find(:all, [SOMETHING HERE]).size

Any idea?

Bob Sanders wrote:

If you want to show the number of consecutive days a user has posted (e.g. "You have posted 5 days in a row"), how would you do it?

This is tricky. What you're after is the number of days since the last day the user didn't post anything. That is, the maximum date before today that does NOT appear for that user. I can't think of a way offhand you could get this in one hit.

One solution is to keep the count in the model. Then, each time a user posts, find the last post date for them and if it was yesterday, update the count, else reset it.

Maybe something like:

Post.count( :conditions => (1..5).collect { |x| "created_at LIKE '#{ ( Date.today - x ).to_s }%'" }.join( ' AND ' ) )

Mark Bush wrote:

Bob Sanders wrote:

If you want to show the number of consecutive days a user has posted (e.g. "You have posted 5 days in a row"), how would you do it?

This is tricky. What you're after is the number of days since the last day the user didn't post anything. That is, the maximum date before today that does NOT appear for that user. I can't think of a way offhand you could get this in one hit.

One solution is to keep the count in the model. Then, each time a user posts, find the last post date for them and if it was yesterday, update the count, else reset it.

That's a great idea, Mark. I didn't think of keeping the count in the model. That's definitely one way to do it.

Greg Donald wrote: