Rails 4 ActiveRecord。其中一个数组中的任何元素都在另一个数组中 [英] Rails 4 ActiveRecord .where any element in one array is in another array
问题描述
我有一个ID列表,看起来像这样:
I have a list of ids that looks something like this:
feed_ids = [1,2,3,4,5] # will be filled with random ids
我有一个Post模型,该模型的属性parent_ids可能看起来像这样:
I have a Post model that has an attribute parent_ids that might look something like this:
parent_ids = [20,14,1]
我想检索parent_ids中的元素与feed_ids中的元素匹配的所有记录
I want to retrieve all records where an element in parent_ids matches an element in feed_ids
nodes = Post.where(parent_ids: feed_ids)
这并没有给我一个错误,但是也没有返回任何记录。
It's not giving me an error but it's also not returning any records.
推荐答案
find
方法可以接受数组。您可以在此处使用数组交集。
The find
method can take in an array. You could use array intersection here.
Post.find(parent_ids & feed_ids)
免责声明
我没有安装Rails,因此我必须凭直觉行事。
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.
这篇关于Rails 4 ActiveRecord。其中一个数组中的任何元素都在另一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!