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...
first.towers.id
will not work You will have to writefirst.towers.first.id