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
方法.
<<
将一个项附加到数组,因此查询将不会运行,而是作为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)
归档时间: |
|
查看次数: |
186 次 |
最近记录: |