如何 return Rails API 中的正确字段?
How to return the correct fields in Rails API?
我有这两个 tables - 用户、帐户。
用户包含身份验证密钥,
帐户包含帐户列表。
如果身份验证密钥正确,我正在尝试获取用户的帐户列表。
所以在控制器中我有 -
def show
@user = User.where(authentication_token: params[:authentication_token])
render json: @user.as_json(
only: [:email, :id, :authentication_token]
),
status: :created
end
这只是 return 用户详细信息。我如何编辑它,以便它首先检查用户是否存在 Authentication_token,然后使用帐户 table 中的用户 ID 来获取帐户列表?
您的问题有点不清楚:如果 authentication_token
不 正确,期望的行为是什么?引发异常?重定向到某个地方?显示一条闪现信息? ...
例如,您可以这样做:
def show
if authenticated_user
render json: authenticated_user.accounts.as_json(
only: [:id, :foo, :bar]
),
status: :ok
else
render json: { errors: { authentication_token: 'Invalid' } },
status: :unauthorized
end
end
private
def authenticated_user
@authenticated_user ||= User.find_by(
authentication_token: params[:authentication_token]
)
end
我有这两个 tables - 用户、帐户。 用户包含身份验证密钥, 帐户包含帐户列表。
如果身份验证密钥正确,我正在尝试获取用户的帐户列表。
所以在控制器中我有 -
def show
@user = User.where(authentication_token: params[:authentication_token])
render json: @user.as_json(
only: [:email, :id, :authentication_token]
),
status: :created
end
这只是 return 用户详细信息。我如何编辑它,以便它首先检查用户是否存在 Authentication_token,然后使用帐户 table 中的用户 ID 来获取帐户列表?
您的问题有点不清楚:如果 authentication_token
不 正确,期望的行为是什么?引发异常?重定向到某个地方?显示一条闪现信息? ...
例如,您可以这样做:
def show
if authenticated_user
render json: authenticated_user.accounts.as_json(
only: [:id, :foo, :bar]
),
status: :ok
else
render json: { errors: { authentication_token: 'Invalid' } },
status: :unauthorized
end
end
private
def authenticated_user
@authenticated_user ||= User.find_by(
authentication_token: params[:authentication_token]
)
end