Search code examples
ruby-on-railsrubyactiverecordactiverecord-relation

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


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?


Solution

  • 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