简体   繁体   中英

Find records where length of array equal to - Rails 4

In my Room model, I have an attribute named available_days , which is being stored as an array.

For example:

Room.first.available_days
=> ["wed", "thurs", "fri"]

What is the best way to find all Rooms where the size of the array is equal to 3?

I've tried something like

Room.where('LENGTH(available_days) = ?', 3)

with no success.

Update: the data type for available_days is a string, but in order to store an array, I am serializing the attribute from my model:

app/models/room.rb

serialize  :available_days

Can't think of a purely sql way of doing it for sqlite since available_days is a string .

But here's one way of doing it without loading all records at once.

rooms = []
Room.in_batches(of: 10).each_record do |r|
  rooms << r if r.available_days.length == 3
end

p rooms

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