21

Here are my simplified models, I have joined models:

class Apartment < ApplicationRecord
  has_many :towers
end

and

class Tower < ApplicationRecord
  belong_to :apartment
end

and then I tried to join both tables in controller. I also tried it in rails console like this :

Apartment.joins(:towers).select('apartments.id', 'apartments.name', 'towers.id' , 'towers.name')

the problem is above query only returns

apartments.id and apartments.name

also tried to use alias like this, still no luck

Apartment.joins(:towers).select('apartments.id', 'apartments.name',
'towers.id as towerid' , 'towers.name as towername')

I have confirmed that all towers have an apartment, I know i could do this to get 1 record

Apartment.joins(:towers).select('apartments.id', 'apartments.name', 'towers.id' , 'towers.name').first.towers.id

and etc, but i need all records and all those fields, please advice.

here is the latest result i got in rails console :

 Apartment Load (1.0ms)  SELECT apartments.id, apartments.name, towers.id as towerid, towers.
    tower_name as towername FROM `apartments` INNER JOIN `towers` ON `towers`.`apt_id` = `
    apartments`.`id`
    => #<ActiveRecord::Relation [#<Apartment id: 5, name: "basura">, #<Apartment id: 5, apt_
    name: "basura">, #<Apartment id: 124, name: "hydra">, #<Apartment id: 124, name: "hy
    dra">, #<Apartment id: 126, name: "mediterania">, #<Apartment id: 126, name: "mediterania">, #<Apartment id: 142, name: "apartement gajah mada">, #<Apartment id: 142, name: "apartement gajah mada">]>

as you can see, above query only return 2 fields, i need the result to be like this :

#<Apartment id: 126, name: "mediterania", tower_id: 12, tower_name: "tower A">, 
#<Apartment id: 126, name: "mediterania", tower_id: 15, tower_name: "tower F">

etcc...

7
  • use 'includes' in place of 'joins' Commented Oct 14, 2016 at 7:01
  • Just for your info. first.towers.id will not work You will have to write first.towers.first.id
    – dnsh
    Commented Oct 14, 2016 at 7:04
  • @GauravGupta tried to use includes in rails console, it throw an error "unknown column 'towers.tower_name'"
    – NomNomNom
    Commented Oct 14, 2016 at 7:14
  • @HendraLim It will not work because towers is activerecord relation you have to do towers.first.name
    – dnsh
    Commented Oct 14, 2016 at 7:21
  • @Dinesh would n't it only returns a single record? could you please put a complete example of your suggestion in answer section.
    – NomNomNom
    Commented Oct 14, 2016 at 7:27

5 Answers 5

28

The only way I see this is possible is using as

q = Apartment.joins(:towers).select('apartments.id, apartments.name, towers.id as t_id, towers.name as t_name')

q.first.t_id
q.first.t_name

Why first.towers.id will not work?

apartment.towers will return ActiveRecord::Associations::CollectionProxy. You can think of it as a collection of towers. In SQL query you are referring to towers table. But when you run apartment.towers.id you are calling id on CollectionProxy object which will not work. You can get first tower using towers.first.

Regarding,

Apt Load (1.0ms)  SELECT apts.id, apts.apt_name, towers.id as towerid, towers.
    tower_name as towername FROM `apts` INNER JOIN `towers` ON `towers`.`apt_id` = `
    apts`.`id`
    => #<ActiveRecord::Relation [#<Apt id: 5, apt_name: "basura">, #<Apt id: 5, apt_
    name: "basura">, #<Apt id: 124, apt_name: "hydra">, #<Apt id: 124, apt_name: "hy
    dra">, #<Apt id: 126, apt_name: "mediterania">, #<Apt id: 126, apt_name: "mediterania">, #<Apt id: 142, apt_name: "apartement gajah mada">, #<Apt id: 142, apt_name: "apartement gajah mada">]>

What you see in console is result returned by inspsect method. The inspect method is not designed to show non column attributes. Hence even if you have towername in memory it will only show attributes which are columns of Apartment model. More about inspect

I also recommend to try following:

Apartment.joins(:towers).pluck('apartments.id, apartments.name, towers.id as t_id, towers.name as t_name')

Above statement will get all data in array. The same result you get with select but select will not load all data in array.

3
  • indeed it return tower name, but the problem it only return 1 record, what i need is to return data like this <Apt id: 126, apt_name: "mediterania", t_id: 12, t_name: "tower A">, #<Apt id: 126, apt_name: "mediterania", t_id:13, t_name: "tower B"> etc etc.
    – NomNomNom
    Commented Oct 14, 2016 at 7:51
  • @HendraLim You have it just like you want. In console it will show only columns which are present in Apt Model.
    – dnsh
    Commented Oct 14, 2016 at 7:56
  • 1
    i have used pluck before, but since it return an array instead of an ORM object, it does not solve my problem, btw i have solved my problem, i guess you are right i still can access tower name and id field, even though it s not showing in console, upvoted, thanks for help.
    – NomNomNom
    Commented Oct 14, 2016 at 9:13
12

You should use

Apartment.joins(:towers).select('apartments.id, apartments.name, towers.id , towers.name')

that is all column names inside a single string.

Refer this.

11
  • can you post the generated sql query ? Or If you are trying in console, just add .to_sql at the end and see if it is generating correct query.
    – Sajan
    Commented Oct 14, 2016 at 6:56
  • here you go : => "SELECT apts.id, apts.apt_name, towers.id, tower.tower_name FROM apts INNER JOIN towers ON towers.apt_id = apts.id"
    – NomNomNom
    Commented Oct 14, 2016 at 6:57
  • this is kinda strange, because i can see the query is generated correctly, but somehow the query result did not reflect it. oh btw, i also tried to check generated query with my first approach, all field in separated string, it also return the same query as your approach.
    – NomNomNom
    Commented Oct 14, 2016 at 6:58
  • 3
    @sajan i have solved the problem, there is nothing wrong with our's initial approach, its just those fields are not showing in console (tower.id, tower.name), but those fields are there, and can be used directly, many thanks, upvoted.
    – NomNomNom
    Commented Oct 14, 2016 at 9:16
  • 3
    This works! It does return all the fields, but it shows only the "Apparment" in the console. .as_json will show you everything is included!
    – leosok
    Commented Dec 4, 2020 at 20:56
7

Rails 7.1 adds support for such queries, now select accepts hash

You can use aliases like this

Apartment
  .joins(:towers)
  .select(
    apartments: { id: :apartment_id, name: :apartment_name },
    towers: { id: :tower_id, name: :tower_name }
  )

It produces such query

SELECT apartments.id AS apartment_id, apartments.name AS apartments_name,
  towers.id AS tower_id, towers.name AS tower_name
FROM apartments
INNER JOIN towers ON towers.apartment_id = apartments.id
2
  • 2
    I tried this (as I prefer to use hashes than strings for queries) but received this error: Unsupported argument type: Hash. Construct an Arel node instead. Commented Feb 13, 2023 at 5:14
  • 2
    That is only supported in Rails 7.1. Commented Sep 28, 2023 at 21:19
0

You can try the alias names like below

Apartment.joins(:towers).select('apartments.id as apartment_id, apartments.name as apartment_name, towers.id as tower_id , towers.name as tower_name)
1
  • Try this. Apartment.joins("OUTER JOIN towers on towers.apartment_id = apartments.id").select('apartments.id as apartment_id, apartments.name as apartment_name, towers.id as tower_id , towers.name as tower_name) Commented Oct 14, 2016 at 8:12
0

You can try this

Apartment.joins(:towers).select('apartments.id as id, apartments.name as apartment_name, towers.id as tower_id , towers.name as tower_name)

you will get the response like this #ActiveRecord::Relation [#<Apt id: 126, apt_name: "mediterania", tower_id: 12, tower_name: "tower A">, #<Apt id: 126, apt_name: "mediterania", tower_id: 15, tower_name: "tower F">]>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.