mrmicrowaveoven
mrmicrowaveoven

Reputation: 185

Returning the original relation in a class method called on a relation

I have a class method on a model called order_by_ids(ids) that is called by an ActiveRecord Relation. Below is an example of its usage:

User.where(id: [1,2,3]).order_by_ids([2,1,3])

...will return Users 1, 2, and 3 in the order of: [2,1,3]

I would like for it to return the original relation (essentially doing nothing) if passed an empty array.

The following returns the entire class, not just the relation it's called on:

return self unless ids.present?

The following works 100%, but it seems inelegant. Also, I think it runs an unnecessary query (seems slower in the console anyway):

return where.not(id: nil) unless ids.present?

Is there a quick way to just return the relation it's called on? I could theoretically make it a scope, but I've been taught to avoid scopes with arguments (see this guide for reference).

Note: I am using Rails 3, so all returns an array. I'm essentially looking for a Rails 4 version of all.

Upvotes: 1

Views: 549

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

The following should preserve the upstream scope chain (returning all, not self):

return all if ids.none?

P.S. Named scopes is a perfectly accepted and conventional way of dealing with queries.

Upvotes: 2

Related Questions