简体   繁体   English

不使用任何方法或使用`all()`生成ActiveRecord :: 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() . 我正在尝试从模型中构建ActiveRecord::Relation对象,而不使用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 . 您会看到,如果在参数中未设置activesmokers ,则@people只是模型,而不是ActiveRecord::Relation

I could throw on all at the end of return @people but there must be a better way. 我可以在return @people结束时抛出all ,但必须有更好的方法。

Thoughts? 有什么想法吗?

You can use the .scoped method: 您可以使用.scoped方法:

@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. 还有一个.unscoped方法 ,基本上执行相同的操作,但忽略所有定义的default_scopes


Rails 4: The method .scoped is deprecated , see @FrederickCheung's answer Rails 4:不建议使用.scoped方法 ,请参阅.scoped的答案

On rails 3.x, scoped is the way to go. 在rails 3.x上,必须先确定scoped However it is deprecated in Rails 4 and removed in Rails 4.1 但是,它已在Rails 4中弃用,在Rails 4.1中已删除。

For rails 4.0 and higher, all just returns a scope, so you would instead write 对于Rails 4.0和更高版本, all函数都只返回一个范围,因此您应该编写

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

return @people

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM