Sql 如何在Rails API中返回正确的字段?
我有两个表-用户、帐户。 用户包含身份验证密钥, Accounts包含帐户列表 如果身份验证密钥正确,我将尝试获取用户的帐户列表 所以在控制器中,我有-Sql 如何在Rails API中返回正确的字段?,sql,ruby,ruby-on-rails-3,Sql,Ruby,Ruby On Rails 3,我有两个表-用户、帐户。 用户包含身份验证密钥, Accounts包含帐户列表 如果身份验证密钥正确,我将尝试获取用户的帐户列表 所以在控制器中,我有- def show @user = User.where(authentication_token: params[:authentication_token]) render json: @user.as_json( only: [:email, :id, :authentication_token]
def show
@user = User.where(authentication_token: params[:authentication_token])
render json: @user.as_json(
only: [:email, :id, :authentication_token]
),
status: :created
end
这将只返回用户详细信息。我如何编辑它,以便它首先检查用户是否存在该身份验证令牌,然后在accounts表中使用UserID来获取帐户列表 您的问题有点不清楚:如果
身份验证\u令牌
是不正确的,那么期望的行为是什么?提出一个例外?重定向到某个地方?显示闪光信息
例如,您可以这样做:
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
@user.accounts
或类似的东西。在执行此操作时,我一直得到未定义的方法“accounts”。accounts表存在,并且经过身份验证的用户也正确。该用户是否有多个帐户?这是我的假设,但你没有在原来的帖子中澄清这一点。