Reputation: 233
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
Reputation: 2432
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.
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
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