新手问题 写组合搜索就有些别的优雅的办法吗?

QueXuQ · 2014年05月29日 · 最后由 xmonkeycn 回复于 2014年05月29日 · 1858 次阅读

写组合搜索就有些别的优雅的办法吗?

product = Product.all
product = product.where(...) if this_params[...].present?
product = product.where(...) if this_params[...].present?
product = product.where(...) if this_params[...].present?
product.page(...)

每次写个组合的搜索就像上面那样,一堆的东西,字段越多,判断就越多,有木有什么好的办法呢?

一般写的和见到的都是不同的组合比如 where, order, include, join 等等。

全部 where 的话应该不需要这么串,直接一个 where(params)就行了吧,空的自然不会出现。

具体还得看代码,不同需求不同方法。

#1 楼 @billy 空的当然会出现 为 nil 的项目会转成 sql xxx IS NULL 所以 一般是 where(params[:xxx].xxx.select{|k,v| v.present?}) 或者 override where 方法 我就是复写了 where 直接丢进去 hash 就可以了

https://github.com/activerecord-hackery/ransack 不过我也还没用过-.- 同写 n 行 where 觉得不爽的路过。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号