BigL
BigL

Reputation: 89

ROR: Creating a method with a parameter

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?

Upvotes: 1

Views: 41

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14890

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 }

Upvotes: 4

Related Questions