mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-01-24 20:36:49 +00:00
Improve queries for serializers
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
require 'open_food_network/enterprise_injection_data'
|
||||
|
||||
module InjectionHelper
|
||||
include SerializerHelper
|
||||
|
||||
def inject_enterprises(enterprises = Enterprise.activated.includes(address: :state).all)
|
||||
inject_json_ams(
|
||||
'enterprises',
|
||||
@@ -11,9 +13,11 @@ module InjectionHelper
|
||||
end
|
||||
|
||||
def inject_enterprise_shopfront_list
|
||||
select_only = required_attributes Enterprise, Api::EnterpriseShopfrontListSerializer
|
||||
|
||||
inject_json_ams(
|
||||
'enterprises',
|
||||
Enterprise.activated.includes(address: :state).all,
|
||||
Enterprise.activated.select(select_only).includes(address: :state).all,
|
||||
Api::EnterpriseShopfrontListSerializer
|
||||
)
|
||||
end
|
||||
|
||||
@@ -3,4 +3,13 @@ module SerializerHelper
|
||||
return [] if ids.blank?
|
||||
ids.map { |id| { id: id } }
|
||||
end
|
||||
|
||||
# Returns an array of the fields a serializer needs from it's object
|
||||
# so we can #select only what the serializer will actually use
|
||||
def required_attributes(model, serializer)
|
||||
model_attributes = model.attribute_names
|
||||
serializer_attributes = serializer._attributes.keys.map(&:to_s)
|
||||
|
||||
(serializer_attributes & model_attributes).map { |attr| "#{model.table_name}.#{attr}" }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
module Api
|
||||
class EnterpriseShopfrontListSerializer < ActiveModel::Serializer
|
||||
attributes :name, :id, :latitude, :longitude, :is_primary_producer, :is_distributor,
|
||||
:visible, :path, :icon, :icon_font, :producer_icon_font
|
||||
:visible, :path, :icon, :icon_font, :producer_icon_font, :address_id, :sells,
|
||||
:permalink
|
||||
|
||||
has_one :address, serializer: Api::AddressSerializer
|
||||
|
||||
|
||||
18
spec/helpers/serializer_helper_spec.rb
Normal file
18
spec/helpers/serializer_helper_spec.rb
Normal file
@@ -0,0 +1,18 @@
|
||||
require 'spec_helper'
|
||||
|
||||
describe SerializerHelper, type: :helper do
|
||||
let(:serializer) do
|
||||
class ExampleEnterpriseSerializer < ActiveModel::Serializer
|
||||
attributes :id, :name
|
||||
end
|
||||
ExampleEnterpriseSerializer
|
||||
end
|
||||
|
||||
describe "#required_attributes" do
|
||||
it "returns only the attributes from the model that the serializer needs to be queried" do
|
||||
required_attributes = helper.required_attributes Enterprise, serializer
|
||||
|
||||
expect(required_attributes).to eq ['enterprises.id', 'enterprises.name']
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user