I have a table with one column called path, which consists of numbers, and another table with two columns which are called id consists of numbers and name consists of words. I want to compare the column path with the column id when they are equals, I want to save the word in the column name which referred to the id in the same table in an array. For example, the only column (path) of the first table is (10, 2, 4) and the first column (id) of the second table is (1, 2, 3), and the second column (name) of the second table is (Tom, Jim, John). Now when the path equals id for this example I mean 2, then I need to store the word "Jim" in an array and so on.
CodePudding user response:
Here is the answer to your exact question, where the corresponding Models for the first and second tables in your example are M1
and M2
, respectively, and array_out
is the desired Array of the names. The values of the column path
are assumed to be Integers.
paths = M1.pluck :path
array_out = M2.where(id: paths).pluck(:name)
EDIT (below)
The answer above incurs two SQL queries. @Eyeslandic pointed out the following will do it in one query only:
M2.where(id: M2.select(:path)).pluck(:name)