Shalafister's Shalafister's - 2 months ago 10
MySQL Question

Rails join 3 table and extract only names as arrays

I have country, city and location tables. I would like to combine 3 of them and get only name columns as arrays. For instance;

Country

id: 1, name: 'Russia', lat: .., lng: ..
id: 2, name: 'France', lat: .., lng: ..
id: 3, name: 'Spain', lat: .., lng: ..


City

id: 1, name: 'Kiev', lat: .., lng: ..
id: 2, name: 'Nice', lat: .., lng: ..
id: 3, name: 'Barcelona', lat: .., lng: ..


Location
Country

id: 1, name: 'Burger Restaurant', lat: .., lng: ..
id: 2, name: 'La baguette', lat: .., lng: ..
id: 3, name: 'Tapas Bar', lat: .., lng: ..


So what I require should look like this;

myArray = ['Russia', 'France', 'Spain', 'Kiev', 'Nice', 'Barcelona', 'Burger Restaurant', 'La baguette', 'Tapas Bar']


The order of the items do not matter, it can be shuffled because I want to use them in
typehead.js
. I also did not want to push them in an array with for loops. I am looking for a faster and efficient way.

Answer Source

You can do this:

def locations
 countries = Country.all.pluck(:name)
  cities = City.all.pluck(:name)
  location_countries = LocationCountry.all.pluck(:name)

  countries + cities + location_countries
end