Home ActiveRecord select columns where one column is an array of a single property from a relation
Reply: 0

ActiveRecord select columns where one column is an array of a single property from a relation

user1424
1#
user1424 Published in May 22, 2018, 9:37 pm
class Building < ActiveRecord::Base
  # id
  # name
  # url

  has_many :floors
end

class Floor < ActiveRecord::Base
  # id
  # building_id
  # name
  # number

  belongs_to :building
end

I want to add a method to the Building model that returns the following:

def self.some_stuff
  [{
    id: "81b0bd96-20e9-4f01-9801-59f3d9b99735",
    url: "http://www.google.com",
    numbers: [4,5,6,7,8,9]
  },
  {
    id: "5de096dd-f282-41cc-8300-b972fb61ea41",
    url: "http://www.yahoo.com",
    numbers: [2,7,11]
  }]
end

Ideally I would like to make this chainable so that I could do the following:

Building.all.limit(100).some_stuff

EDIT 1:

Here is how what I am trying to get at looks like in postgresql:

SELECT
    B.id,
    B.url,
    array_agg(F.floor_number) AS numbers
FROM
    buildings AS B
    LEFT OUTER JOIN floors AS F ON
        F.building_id = B.id
GROUP BY
    B.uuid;

EDIT 2:

The following gives me the data I want but in a really crappy format (because of pluck). If I change pluck to select it breaks.

def self.some_stuff
  fields = "buildings.id, buildings.url"
  joins(:floors)
    .includes(:floors)
    .group(fields)
    .pluck("#{fields}, array_agg(floors.floor_number)")
end
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312247 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO