我有一个字符串数组,用作模型中 where
调用的参数。
如何附加模型中的每个字符串 where
调用并返回事件记录关系以进行额外的 limit
调用
我尝试了以下但它只将第一项添加到 where 子句
array = ['active = true', 'expired = false', 'created_at > 2017-04-18 10:36:28']
array.reduce { | item | Post.where(item) }
返回
Posts.where('active = true')
而我乞求
Posts.where('active = true').where('expired = false').where('created_at > 2017-04-18 10:36:28')
谢谢。
最佳答案
只需将数组的元素join
成一个字符串:
array.join(' AND ')
#=> "active = true AND expired = false AND created_at > 2017-04-18 10:36:28"
并使用它:
Post.where(array.join(' AND '))
附言
created_at > 2017-04-18 10:36:28
可能会引发语法错误,但这不在问题范围内。
关于ruby-on-rails - 编写具有字符串条件数组的 ActiveRecord 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43674755/