Reputation: 25542
This is my "dynamic" scope:
def all_games(conditions = {})
scope = games.includes(:stats).scoped {}
scope = scope.where sport_position_id: conditions[:sport_position_id] unless conditions[:sport_position_id].nil?
scope = scope.where sport_id: conditions[:sport_id] unless conditions[:sport_id].nil?
scope = scope.where team: conditions[:team]
scope.order(:date)
end
The method above is in a module that is included with my User
model.
So you would access this in code, like so:
u = User.find(1)
u.all_games(sport_position_id: params[:sport_position_id], sport_id: current_sport.id, team: params[:team])
When doing some Google searching for dynamic scopes, I came across Ryan Bate's RailsCast on anonymous scopes
(http://railscasts.com/episodes/112-anonymous-scopes). I modified it since I am using Rails 3, but was wondering, if I was on the right path when it comes to writing dynamic scopes?
I find myself sometimes writing dynamic scopes because of the nature of some complex API's I am writing.
Upvotes: 0
Views: 45