Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Build a Todo List Application with Rails 4 Build a Todo List Application with Rails 4 Viewing Todo Lists

Still do not understand what for is the scope :complete and the scope :incomplete

Hi, jason added this code in the todo_item.rb controller

scope :complete, -> { where(%Q|completed_at is not null|) }
  scope :incomplete, -> { where(completed_at: nil) }

when is this used? I cannot find where is this used, I just know that it works but i do not understand where is used, and when, I mean Im very lost in what Jason did regarding this matter in the video...

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

Scopes are a very nice thing and Jason doesn't really say much about how they work. You create scopes and give them names like complete and incomplete and then you can specify what criteria have to be met for an item to be in that scope. You can treat them as methods that return only some of the elements from the database table. Your basic scope is all:

TodoItem.all

This would return all the TodoItem class elements. But if you define those scopes and then use them like this:

TodoItem.complete

Then this will return only the elements that have the completed_at attribute filled in (which means the complete button was clicked for them and this attribute was added).

Jason uses them in the custom method in the video at approximately 4:37. Here's some more documentation:

http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html

Make sure you play a bit with scopes and that you understand them. This will be very useful in your future projects :)

Thanks ! you rock ! =)