trigun0x2
trigun0x2

Reputation: 233

Active Record Limiting All Queries to a Date Range

I want to be able to limit all queries on a controller to say y > Date > x. I tried to use a before_filter but couldn't find a good solution. One possible solution would be to go to each query and add an additional where filter, but I feel like there's a better way to do it.

Any ideas?

Upvotes: 1

Views: 813

Answers (2)

jstim
jstim

Reputation: 2432

default_scope

If you want all requests to a model to have the same constraints, try default_scope

# models/activity.rb
class Activity < ActiveRecord::Base
  default_scope { where("date between ? and ?", 5.days.ago, Date.current) }
end

So if you call:

Activity.all

You will only get back activities in the date range specified by the default_scope.

scopes

If you instead want to be able to specify a date range for different queries, you could create a scope that you would have to explicitly call:

# models/activity.rb
class Activity < ActiveRecord::Base
  scope :between_dates, ->(begin_date,end_date) {
    where("date between ? and ?", begin_date, end_date)
  }
end

Which you would call in your controller like:

Activity.between_dates(5.days.ago, Date.current)

Upvotes: 4

TrevTheDev
TrevTheDev

Reputation: 2737

jstim's answer is likely the right one for your problem and the limiting should be done in the MODEL and not the controller. MODELs work with data and Controllers handle the interaction between models, views and requests.

Also see http://guides.rubyonrails.org/active_record_querying.html#scopes

If however it MUST be done in the controller then simply apply the filter to your instance variables. e.g. @post.default_scope { where("date between ? and ?", 5.days.ago, Date.current) }

Upvotes: 0

Related Questions