Returns a hash representing a model and it's associated data. Useful for building an JSON API.
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
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
{
"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 thecreated_at
,updated_at
andid
attributes are not returned. Theinclude
option allows us to load associated records. Note that second level and higher order associations work as well.