【问题标题】:Equivalent to += (plus equal) to add scopes with ActiveRecord in rails等价于 +=(加等于)在 Rails 中添加带有 ActiveRecord 的范围
【发布时间】:2017-02-16 22:44:25
【问题描述】:

我想根据条件链接我的范围。但是由于 ActiveRecord 中对范围的惰性求值,只有最后一个分配被考虑在内。

@list = Product.all
if condition 1
  @list = Product.scope1
if condition 2
 @list = Product.scope2
if condition 3
  @list = Product.scope3
...
@list 

我希望能够一个接一个地积累作用域。

【问题讨论】:

    标签: ruby-on-rails activerecord scope


    【解决方案1】:

    像这样把它们串起来

    @list = Product.all
    @list = @list.scope1 if condition1
    @list = @list.scope2 if condition2
    @list
    

    那么最后@list持有你想要的元素。

    【讨论】:

    • 谢谢!现在似乎很明显,我有了答案。
    猜你喜欢
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 2014-06-07
    相关资源
    最近更新 更多