[英]Ransack filter by multiple values or nil
I have an API written using jsonapi.rb and Ransack.我有一个使用 jsonapi.rb 和 Ransack 编写的 API。
My model has a Car with color attribute, which is an integer or nil.我的 model 有一个带有颜色属性的汽车,它是 integer 或零。 I would like to be able to filter this attribute by multiple color numbers or empty values.我希望能够通过多个颜色数字或空值过滤此属性。 It would look like this:它看起来像这样:
/cars?filter[color_in]=1,2,nil
Ransack can search by multiple values, or it can filter by null values. Ransack 可以按多个值搜索,也可以按 null 值过滤。 But how can I pass an empty value to Ransack here?但是我怎样才能在这里将一个空值传递给 Ransack?
An easy way out is to convert a null to another value and search by it.一个简单的方法是将 null 转换为另一个值并通过它进行搜索。 In my case column is an integer, so I want to convert null to 0 for all attributes I want to filter by.在我的情况下,列是 integer,所以我想将 null 转换为 0,以获得我想要过滤的所有属性。
Add to model:添加到 model:
ransacker :color do
Arel.sql('COALESCE(color, 0)')
end
Then search with:然后搜索:
/cars?filter[color_in]=1,2,0
So query will look like:所以查询将如下所示:
WHERE COALESCE(color, 0) IN ('1', '2', '0')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.