swingfuture
swingfuture

Reputation: 1108

How to use filter in Model

A model named Post, corresponding to posts table in the db. Post.find_within_4_days can get me the last 4 days posts. All my following operation would be based on the past 4 days posts. I would like it to be filtered or defined somewhere, so I can just reference it instead of repeating Post.find_within_4_days everywhere. How do I do in Post model?

Upvotes: 1

Views: 89

Answers (3)

bricker
bricker

Reputation: 8941

Even more flexible:

class Post < ActiveRecord::Base
  scope :within, lambda { |time| where("created_at > ?", Time.zone.now - time }
end

Post.within(4.days)

Upvotes: 2

Nils Landt
Nils Landt

Reputation: 3134

Assuming you're using Rails 3, you could use a name scope like this:

class Post < ActiveRecord::Base
  scope :within_4_days, where(# however you find your 4 day old posts #)
end

You could then use Post.within_4_days everywhere.

If you want only the posts of the last 4 days anywhere, you could set up a default scope instead:

class Post < ActiveRecord::Base
  default_scope where(# however you find your 4 day old posts #)
end

after which (for example) Post.all would only return the posts of the last 4 days.

Upvotes: 3

sarvavijJana
sarvavijJana

Reputation: 1212

default_scope and scope are great options for your case, refer to this wonderful site

Upvotes: 1

Related Questions