Sha256: 8057bac3487f9a56424a79313696d2b85a2b5d89b730187e0995773751600664

Contents?: true

Size: 1.06 KB

Versions: 7

Compression:

Stored size: 1.06 KB

Contents

require 'action_controller'

module Fields
  module Serializer
    module ActionController
      extend ActiveSupport::Concern


      # Render the result of an ActiveRecord query including only the fields specified if any
      #   or the whole serialized objects.
      #
      # @param  [ActiveRecord_Relation] query - The query to render in json
      # @option options [Array] :fields       - The list of fields to return in json api syntax
      # @option options [Class] :model_class  - The model class of the objects to be queried to optimize db hits.
      # @option options [Hash]  :options      - Any other valid option to render method.
      def render_json_fields(query, **options)
        fields      = options.delete(:fields)
        model_class = options.delete(:model_class)
        if fields
          query = query.includes(*model_class.fields_to_includes(fields))
          options.merge!(each_serializer: FieldSerializer, fields: Array(fields))
          options.delete(:include)
        end
        render options.merge!(json: query.to_a)
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
fields-serializer-0.3.2 lib/fields/serializer/action_controller.rb
fields-serializer-0.3.1 lib/fields/serializer/action_controller.rb
fields-serializer-0.3.0 lib/fields/serializer/action_controller.rb
fields-serializer-0.2.4 lib/fields/serializer/action_controller.rb
fields-serializer-0.2.3 lib/fields/serializer/action_controller.rb
fields-serializer-0.2.2 lib/fields/serializer/action_controller.rb
fields-serializer-0.2.1 lib/fields/serializer/action_controller.rb