简体   繁体   中英

Ransack filter by multiple values or nil

I have an API written using jsonapi.rb and Ransack.

My model has a Car with color attribute, which is an integer or nil. 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. But how can I pass an empty value to Ransack here?

An easy way out is to convert a null to another value and search by it. In my case column is an integer, so I want to convert null to 0 for all attributes I want to filter by.

Add to 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM