Skip to content

JSON API nicer include syntax #1128

Closed
Closed
@willcosgrove

Description

I have a lot of nested associations in my app, and was getting tired of writing really long strings/arrays for the include option. So I wrote a little helper that turns an include that looks like this:

render json: @project_group, include: [projects: [project_tasks: [:part, :specification_revisions, :technique, :estimated_by, :comments, task: [:area]]]]

into an include value that looks like that

render json: @project_group, include: ["projects", "projects.project_tasks", "projects.project_tasks.task", "projects.project_tasks.task.area", "projects.project_tasks.part", "projects.project_tasks.specification_revisions", "projects.project_tasks.technique", "projects.project_tasks.estimated_by", "projects.project_tasks.comments"]

I tried to follow the format of what you can pass in to ActiveRecord::Relation#includes method.

It's a little messy but something along these lines:

  def sanitize_includes(includes, nest: [])
    case includes
    when Array
      includes.flat_map { |include|
        case include
        when Hash
          include.map { |key, value|
            [
              (nest + [key]).join('.'),
              sanitize_includes(value, nest: nest.push(key)),
            ]
          }
        else
          (nest + [include]).join('.')
        end
      }.flatten
    else
      includes
    end
  end

Does this sound helpful to anyone else? I wouldn't mind submitting a PR if it sounds like people are interested.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions