简体   繁体   中英

Rails 4 ActiveRecord .where any element in one array is in another array

I have a list of ids that looks something like this:

feed_ids = [1,2,3,4,5] # will be filled with random ids

I have a Post model that has an attribute parent_ids that might look something like this:

parent_ids = [20,14,1]

I want to retrieve all records where an element in parent_ids matches an element in feed_ids

I tried this but it's not working:

nodes = Post.where(parent_ids: feed_ids)

It's not giving me an error but it's also not returning any records.

The find method can take in an array. You could use array intersection here.

Post.find(parent_ids & feed_ids)

Disclaimer

I do not have Rails installed, so I have to go by my instinct.

Also, this might not be the most efficient solution if you have a large data-set. But with relatively few records, it should be fine.

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