Scope

Wesley Spencer
2 min readFeb 24, 2021

Upon my Phase3 review with flatiron I came to a strong halt when my reviewer asked me to write a scope method for acquiring the article with the most comments. This seemed simple with a max_by method, however understanding how scope works is crucial and beneficial, because using a scope method for this situation is faster at acquiring the information rather than using the max_by method. Simple syntax does not always mean it is better to use.

When using scope methods we are querying specifically to certain parts of our database. Making scope of information smaller to query on.

1) We use .joins on our articles and comments to link the relationship between the two.
2)We use .group to group the articles with comments by the article_id(which is a foreign key in our comments table.)
3)We use .order to organize the comments with which allows us to specify how we’d like to order our attributes.
4)We pass in ‘COUNT(comments.id) DESC’ because we are counting the article comments by their id and listing the count in DESCENDING order.
5)Last is our .limit. This gives us a specific number of objects based on argument. I did my top 5 articles with the most comments.

Breaking this scope method down has really helped me understand how scope is better for querying data out of our database. Its helped me understand when to use it in situations like this one and why its better than other methods. Not only is it faster, but its actually not as scary as it looks as well. I plan on working more with scope methods in the future!

--

--