diff --git a/app/helpers/injection_helper.rb b/app/helpers/injection_helper.rb index d3e3989d95..87f3efe1d7 100644 --- a/app/helpers/injection_helper.rb +++ b/app/helpers/injection_helper.rb @@ -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 diff --git a/app/helpers/serializer_helper.rb b/app/helpers/serializer_helper.rb index ab39e8c252..539e826bfc 100644 --- a/app/helpers/serializer_helper.rb +++ b/app/helpers/serializer_helper.rb @@ -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 diff --git a/app/serializers/api/enterprise_shopfront_list_serializer.rb b/app/serializers/api/enterprise_shopfront_list_serializer.rb index 30b5ed3590..a8ded21bf1 100644 --- a/app/serializers/api/enterprise_shopfront_list_serializer.rb +++ b/app/serializers/api/enterprise_shopfront_list_serializer.rb @@ -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 diff --git a/spec/helpers/serializer_helper_spec.rb b/spec/helpers/serializer_helper_spec.rb new file mode 100644 index 0000000000..2cc66073f3 --- /dev/null +++ b/spec/helpers/serializer_helper_spec.rb @@ -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