Generate an ActiveRecord::Relation without any methods or using `all()`

189 views Asked by At

Seemingly simple question.

I'm trying to build a ActiveRecord::Relation object from a model without using a method like where(). For example:

@people = Person

@people.where( status: 'active' ) if params(:active)
@people.where( is_smoker: true )  if params(:smokers)

return @people

You can see that if neither active or smokers is set in the params, @people is just the model, not an ActiveRecord::Relation.

I could throw on all at the end of return @people but there must be a better way.

Thoughts?

2

There are 2 answers

2
MrYoshiji On BEST ANSWER

You can use the .scoped method:

@people = Person.scoped

@people.where( status: 'active' ) if params(:active)
@people.where( is_smoker: true )  if params(:smokers)

return @people

There is also the .unscoped method which basically does the same thing BUT ignores all the default_scopes defined.


Rails 4: The method .scoped is deprecated, see @FrederickCheung's answer

1
Frederick Cheung On

On rails 3.x, scoped is the way to go. However it is deprecated in Rails 4 and removed in Rails 4.1

For rails 4.0 and higher, all just returns a scope, so you would instead write

@people = Person.all
@people.where( status: 'active' ) if params(:active)
@people.where( is_smoker: true )  if params(:smokers)

return @people