Search for a null value using Ransack 'eq' predicate

老子叫甜甜 提交于 2020-01-03 15:58:37

问题


Using the 'eq' predicate with a blank value, Ransack will cancel out that predicate. Which is obviously handy to have an "All" option in your select.

But what if I want to add an option in my <select> for null values too? In order words how to produce the SQL query SELECT * FROM spree_orders WHERE order_cycle_id = NULL using the 'eq' predicate.

My test code (with results) is below. What I would like is to filter out the Orders where order_cycle_id == nil

Spree::Order.search(order_cycle_id_eq: nil).result.map(&:order_cycle_id)
Spree::Order Load (2.2ms)  SELECT "spree_orders".* FROM "spree_orders" 
 => [nil, 1, nil, nil, nil, nil, nil, nil, 1, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 4, nil, 4, nil, nil, nil, nil] 

The second option is what I'd like to add to my select. I've tried 'null', 'nil', nil, etc..

<select id="q_order_cycle_id_eq" name="q[order_cycle_id_eq]">
  <option value="">All</option>
  <option value="nil">No Order Cycle</option>
  <option value="1">Order Cycle 1</option>
  <option value="2">Order Cycle 2</option>
</select>

回答1:


Try this in console:

Spree::Order.search(order_cycle_id_null: true)

In html view set and then in your controller change ransack query



来源:https://stackoverflow.com/questions/18730792/search-for-a-null-value-using-ransack-eq-predicate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!