I have several objects that all have an approved field.
What would be the best way to implement a scope to use across all models?
For example, I have a sighting object and a comment object. They both have to be approved by an admin before being availalbe to the public.
So how can I create a scope that returns comment.approved as well as sighting.approved respectively without repeating it on each model? Is this where concerns comes into play?
While just declaring a scope in each model is fine if you just want the scoping functionality. Using an
ActiveSupport::Concernwill give you the ability to add additional methods as well if that’s something you think is going to happen. Here’s an example:Then you can make calls like
Sighting.approvedandComment.approvedto get the appropriate list of approved records. You also get theunapprovemethod and can do something likeComment.approved.first.unapprove.In this example, I’ve also included
default_scopewhich will mean that calls likeSighting.allorComment.allwill return only unapproved items. I included this just as an example, it may not be applicable to your implementation.