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

荒凉一梦 提交于 2019-12-13 19:57:54

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/38235463/rails-4-activerecord-where-any-element-in-one-array-is-in-another-array

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