有条件地将模型附加到收集

Jef*_*eff 2 collections ruby-on-rails ruby-on-rails-4

我试图有条件地建立一个模型列表.即

@items = []

if some_condition
    @items << MyModel.where(...)
end

if another_condition
    @items << MyModel.where(...)
end

...
Run Code Online (Sandbox Code Playgroud)

这不起作用.它实际上会构建一个正确对象的数组,但是当我访问数组中项目的字段和关系时,它们"找不到".我尝试了一些其他的东西像@items = MyModel.none@items = {}.merge,但没有工作.我似乎无法弄清楚这一点.

有条件地建立像这样的集合的最佳方法是什么?

更新我希望能够维护,Relation以便我可以继续查询它.where,.first以及其余的Relation方法.

akh*_*bis 5

<<将一个项附加到数组,因此查询将不会运行,而是作为a附加ActiveRecord::Relation,如果使用all,最终会得到一个数组数组.您应该使用concat附加整个集合(+=也将工作,但如果您的查询返回大量记录,将实例化影响性能的不必要的临时数组):

@items = []

if some_condition
    @items.concat(MyModel.where(...))
end

if another_condition
    @items.concat(MyModel.where(...))
end
Run Code Online (Sandbox Code Playgroud)

  • 没关系,我只是将`@items = []`切换回`@items = MyModel.none`并按现在我需要的方式工作. (2认同)