Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion app/controllers/organizations_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ class OrganizationsController < ApplicationController
# GET /organizations
# GET /organizations.json
def index
@organizations = Organization.all
@organizations = if request.format.html?
Organization.with_hq_names_and_store_count.all
else
Organization.with_hq_and_store_names.all
end
end

# GET /organizations/1
Expand Down
35 changes: 35 additions & 0 deletions app/models/organization.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,39 @@
class Organization < ApplicationRecord
has_many :hqs
has_many :stores, through: :hqs

scope :with_hq_names_and_store_count, -> do
select(%(
organizations.*,
(SELECT array_agg(
hqs.name ||
':' ||
countries.name ||
'(' ||
(SELECT count(id) FROM stores WHERE stores.hq_id = hqs.id) ||
')'
)
FROM hqs
JOIN countries ON countries.id = hqs.country_id
WHERE hqs.organization_id = organizations.id
) AS hq_data
))
end

scope :with_hq_and_store_names, -> do
select(%(
organizations.*,
(SELECT array_agg(json_build_object(
'id', hqs.id,
'name', hqs.name,
'country_name', countries.name,
'store_count', (SELECT count(id) FROM stores WHERE stores.hq_id = hqs.id),
'store_list', (SELECT array_agg(json_build_object('id', id, 'name', name)) FROM stores WHERE stores.hq_id = hqs.id)
))
FROM hqs
JOIN countries ON countries.id = hqs.country_id
WHERE hqs.organization_id = organizations.id
) AS hq_data
))
end
end
4 changes: 2 additions & 2 deletions app/views/organizations/_hq_list.html.erb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<% organization.hqs.each do |hq| %>
<%= hq.name %>: <%= hq.country.name %> (<%= hq.stores.count %> stores) <br>
<% organization.hq_data.each do |hq| %>
<%= hq %> <br>
<% end %>
12 changes: 5 additions & 7 deletions app/views/organizations/_organization.json.jbuilder
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ json.extract! organization, :id, :name, :address, :contact_name, :contact_phone,

json.url organization_url(organization, format: :json)

json.hqs organization.hqs do |hq|
json.extract! hq, :id, :name
json.hqs organization.hq_data do |hq|
json.extract! hq, 'id', 'name'

json.country hq.country.name
json.store_count hq.stores.count
json.country hq['country_name']
json.store_count hq['store_count']

json.stores hq.stores do |store|
json.extract! store, :id, :name
end
json.stores hq['store_list']
end