ruby-on-rails - 在 rails 中将部分 pg 数据库条目作为 JSON 返回

标签 ruby-on-rails json ruby database postgresql

我有一个使用 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/

相关文章:

ruby-on-rails - rails 2.3.5 : How do I add an :id field to a namespace?

javascript - 使用 JSON 将分类数据从 SQL 导入到 C3.js

ios - 调用中的额外参数 'error' - 无法构建我的 Xcode 项目

带有提供功能的 Rails HTML 编码/转义

ruby-on-rails - 以简单形式更改ID

ruby-on-rails - 获取特定工作日的最接近日期

ruby-on-rails - Rails 应用程序在下订单和更改交付状态后不发送电子邮件,它只是崩溃了

json - 将具有多个级别的 json 读入 DataFrame [python]

ruby - 如何在命名空间类中包含模块?

ruby-on-rails - 使用 native gem 在 Heroku 上调试段错误