我有一个使用 postgresql 作为数据库的 RoR 应用程序
目前,我有这段代码:
def return_mssg_as_json
id = params[:id].to_i
@message = Message.find(id)
render json: @message
end
它返回这个 JSON:
{"id":13,"created_at":"2017-10-27T19:03:52.196Z","updated_at":"2017-10-27T19:03:52.196Z","text":"ASDF"}
如何让它只返回 {"text":"ASDF"}
最佳答案
这里有几件事......
首先,你不需要在这里做to_i
:
def return_mssg_as_json
id = params[:id].to_i
@message = Message.find(id)
render json: @message
end
你可以这样做:
def return_mssg_as_json
@message = Message.find(params[:id])
render json: @message
end
现在,如果任何您可能会收到一个没有匹配记录的id
,您可能想要执行如下操作:
def return_mssg_as_json
begin
@message = Message.find(params[:id])
render json: @message
rescue ActiveRecord::RecordNotFound
render json: {errors: :not_found}, status: :not_found
end
end
否则,如果您的记录不存在,您将遇到未处理的严重错误。但是,您可以这样做:
def return_mssg_as_json
if @message = Message.find_by(id: params[:id])
render json: @message
else
render json: {errors: :not_found}, status: :not_found
end
end
现在,回到您的主要问题,您可以这样做(如已接受的答案)
def return_mssg_as_json
if @message = Message.find_by(id: params[:id])
render json: { message: @message[:text] }
else
render json: {errors: :not_found}, status: :not_found
end
end
虽然,为了节省三个字符,您似乎可以这样做:
def return_mssg_as_json
if @message = Message.find_by(id: params[:id])
render json: { message: @message.text }
else
render json: {errors: :not_found}, status: :not_found
end
end
这是一个很好的答案!但是,将来,如果你想从 @message
返回多个值(例如),你可以做类似的事情(假设 @message
响应 foo
和 bar
):
def return_mssg_as_json
if @message = Message.find_by(id: params[:id])
render json: @message.attributes.with_indifferent_access.slice(:text, :foo, :bar)
else
render json: {errors: :not_found}, status: :not_found
end
end
这个位:
@message.attributes
将记录转换为其值的散列。这个位:
.with_indifferent_access
允许您使用符号而不是字符串来选择键值对。这一点:
.slice(:text, :foo, :bar)
指定要返回的键值对。因此,这将返回类似以下内容的内容(自然是 JSON 格式):
{text: 'blah', foo: 'blah', bar: 'blah'}
现在,在您的示例中,您不需要text
,您需要message
。所以,你可以这样做:
def return_mssg_as_json
if @message = Message.find_by(id: params[:id])
attr = @message.attributes.with_indifferent_access
render json: attr.slice(:foo, :bar).merge!(message: attr[:text])
else
render json: {errors: :not_found}, status: :not_found
end
end
这将返回类似以下内容的内容(自然是 JSON 格式):
{message: 'blah', foo: 'blah', bar: 'blah'}
关于ruby-on-rails - 在 rails 中将部分 pg 数据库条目作为 JSON 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47099698/