Petran
Petran

Reputation: 8067

Rails scope with a collection

I work on a project and I bumb into a scope use that I didn't know. I have those two definitions :

Class Mymodel
scope :active, where({ active: true })

Class SecondModel
has_many :mymodel

And then I used them like :

instance_var = SecondModel.new
instance_var.mymodels.active

This thing actually works my question is if it's a good way of doing it and how does it work since the scope is equivalent with a class method ? I use mongoid for the database part.

Upvotes: 0

Views: 743

Answers (1)

xlembouras
xlembouras

Reputation: 8295

It works because
instance_var.mymodels can be a Mongoid::Criteria instance.

So it can accept all scopes of Mymodel.

Now the practical difference between scopes and class methods in ActiveRecord (and as far as I remember the same goes for Mongoid) is that scopes must return a relation.

There is no problem in using relations and scopes that way, actually it is very logical and it is the way we normally use them.

Upvotes: 2

Related Questions