1

I have an admins dashboard which displays posts created in the last 24 hours, 7 days, 28 days etc.

def index @1DayPosts = Post.where(created_at: 1.days.ago..DateTime.now).count @7DaysPosts = Post.where(created_at: 7.days.ago..DateTime.now).count @28DaysPosts = Post.where(created_at: 28.days.ago..DateTime.now).count end 

How could I make this into one line? Something like the below:

def index @calculatePosts(a) = Post.where(created_at: a.days.ago..DateTime.now).count end 

Then in the view I could do:

=@calculatePosts(1) 

Or would I need to create a new method?

def calculatePosts(a) @calculatePost = Post.where(created_at: a.days.ago..DateTime.now).count end 

How would I then call this in the index view?

1 Answer 1

4

Your best bet would be to create a scope on the Post model.

class Post ... scope :last_x_days, -> (x) { where(created_at: x.days.ago..Time.zone.now) } end 

Then you can call that anywhere really, in your view or controller like this.

@last_10_days = Post.last_x_days(10).count 

EDIT:

You could do this also, but scopes are meant to be chain-able, so this is discouraged, though not wrong.

scope :last_x_days_count, -> (x) { where(created_at: x.days.ago..Time.zone.now).count } 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the solution! Is it better practice to call @last_10_days = Post.last_x_days(10).count in the controller and then in the view just call @last_10_days ? Or is better to just call @last_10_days = Post.last_x_days(10).count in the view? Or does it not matter?
Does not really matter, you can just call Post.last_x_days(10).count in the view directly, don't really need @last_10_days unless you're using it in multiple places in the view.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.