【发布时间】:2016-03-08 00:10:33
【问题描述】:
您好,我正在创建一个 API。我有一个 user 和 profile 模型。用户 has_one 个人资料。
当我得到一个用户端点时,我想在端点中包含配置文件信息(属性)。
到目前为止,我的终点是这样的
{
"data" => {
"id" => user.id.to_s,
"type" => "users",
"attributes" => {
"email" => user.email
},
"relationships" => {
"profile" => {
"data" => {
"id" => user.profile.id.to_s,
"type" => "profiles"
}
}
}
}
}
应该是这样的
{
"data" => {
"id" => User.last.id.to_s,
"type" => "users",
"attributes" => {
"email" => new_email
},
"relationships" => {
"profile" => {
"data" => {
"id" => User.last.profile.id.to_s,
"type" => "profiles"
}
}
}
}],
"included": [
{
"type": "profiles",
"id": "42",
"attributes": {
"first_name": "John",
"last_name": "Smith"
}
}
]
}
这是我的用户序列化程序
class UserSerializer < ActiveModel::Serializer
attributes :email
has_one :profile
end
这是我在用户控制器中的显示操作
module V1
class UsersController < ApiController
before_action :set_user, only: [:show, :update, :destroy]
def show
render json: @user, include: params[:include], status: :ok
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
attribute_params.permit(:email, :password, roles: [])
end
def assign_roles
end
end
end
【问题讨论】:
-
如果您使用的是 AMS 0.9.3,您可以使用#serialization_options 传递选项,请参阅stackoverflow.com/a/26780514/5086701
标签: ruby-on-rails ruby json ruby-on-rails-4