Active Record Scopes
January 20, 2014
This morning I continued to work on my Daily Weight App so that I could add some more functionality to it. Currently I’m only storing weight entries for each day, but I’m not doing any calculations on the data, like total weight loss and weight loss percentage.
My current model only had a default_scope which will be applied to all other scopes you create. So the first matter of business was to replace this default scope with a non default scope and create another scope that sorted things in ascending order so that I can properly get the first and last values.
Here is an example of a couple of scopes inside of your model:
scope :desc, -> { order('weighed_on DESC') }
scope :asc, -> { order('weigned_on ASC') }
And then inside of your controller they can be called with:
@weight_entries = @user.weight_entries.desc.paginate(page: params[:page])
@first = @user.weight_entries.asc.first
@last = @user.weight_entries.asc.last
Here are some links to resources if you want to learn more about scopes:
- http://railscasts.com/episodes/215-advanced-queries-in-rails-3?view=asciicast
- http://guides.rubyonrails.org/active_record_querying.html