Sha256: 816f53ab92b94d3201ace74aebeb198ee000a5b7f9770a516a4d1327864da51d

Contents?: true

Size: 1.18 KB

Versions: 6

Compression:

Stored size: 1.18 KB

Contents

require 'action_controller'

module Fields
  module Serializer
    module ActionController
      extend ActiveSupport::Concern

      # Render the result of an ActiveRecord::Relation query including only the fields specified
      #
      # @param  [ActiveRecord::Relation] query - The query to render in json
      # @param  [Boolean] optimize_query       - Add outer joins to the query to prevent a db query per serialized object.
      # @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, optimize_query: true, **options)
        fields      = options.delete(:fields)
        model_class = options.delete(:model_class)
        if fields.present?
          query = query.includes(*model_class.fields_to_includes(fields)) if optimize_query
          options.merge!(each_serializer: model_class.fields_serializer(fields), include: "**")
        end
        render options.merge!(json: query.to_a)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
fields-serializer-0.8.4 lib/fields/serializer/action_controller.rb
fields-serializer-0.8.3 lib/fields/serializer/action_controller.rb
fields-serializer-0.8.2 lib/fields/serializer/action_controller.rb
fields-serializer-0.8.1 lib/fields/serializer/action_controller.rb
fields-serializer-0.8.0 lib/fields/serializer/action_controller.rb
fields-serializer-0.7.0 lib/fields/serializer/action_controller.rb