Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Last active February 17, 2022 21:47
Show Gist options
  • Save stevepolitodesign/9285e4f16c42869c6a20278744428775 to your computer and use it in GitHub Desktop.
Save stevepolitodesign/9285e4f16c42869c6a20278744428775 to your computer and use it in GitHub Desktop.
Rails as_json API Example

Rails as_json API Example

Returns a hash representing a model and it's associated data. Useful for building an JSON API.

Associations

class User < ApplicationRecord
  has_many :injuries
  has_many :appointments, through: :injuries

  has_one :active_injury, -> { active }, class_name: "Injury"
end

class Injury < ApplicationRecord
  belongs_to :user

  has_many :appointments
end

Controller

class UserController < ApplicationController
  def show
    @user = User.find(params[:id])

    render json: {
      patient: @user.as_json(
        only: [
          :first_name,
          :last_name,
          :email,
          :phone_number,
          :timezone,
          :latest_activity_on
        ],
        include: {
          active_injury: {
            include: :appointments
          }
        }
      )
    }  
  end
end

Output

{
  "patient": {
    "first_name": "Alice",
    "last_name": "Johnson",
    "email": "[email protected]",
    "phone_number": "5554443333",
    "timezone": "America/Juneau",
    "latest_activity_on": "2022-02-17",
    "active_injury": {
      "id": 2073,
      "user_id": 2782,
      "created_at": "2022-02-10T21:14:07Z",
      "updated_at": "2022-02-17T21:14:07Z",
      "appointments": [
        {
          "id": 810,
          "starts_at": "2022-02-24T21:14:07Z",
          "created_at": "2022-02-17T21:14:07Z",
          "updated_at": "2022-02-17T21:14:07Z",
          "injury_id": 2073,
        }
      ]
    }
  }
}

What's Going On Here?

  • The as_json method returns a hash representing the model.
  • The only option allows us to specificy what attribues we want to return. Note the the created_at, updated_at and id attributes are not returned. The include option allows us to load associated records. Note that second level and higher order associations work as well.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment