【问题标题】:How can I configure my API to send an ID rather than a name via JSON?如何配置我的 API 以通过 JSON 发送 ID 而不是名称?
【发布时间】:2015-02-20 18:01:44
【问题描述】:

我正在用 Ruby 配置一个基本的 API。它包含两个简单的表和一个关联表,但我的连接表给了我一个应该很容易解决的问题。当我在浏览器中打开视图时,它会显示对象name(在本例中为people)。但是,在 view.json 中,它显示了 id。我希望 API 以 JSON 格式发送 name 而不是 id。我怎样才能做到这一点?我的 API 配置如下:

json.array!(@leituras) do |leitura|
  json.extract! leitura, :id, :pessoa_id, :livro_id
  json.url leitura_url(leitura, format: :json)
end

【问题讨论】:

    标签: ruby-on-rails ruby json api


    【解决方案1】:

    您应该尝试 RABL https://github.com/nesquena/rabl。 RABL 实现了一个新模板以将 Json、xml、... 呈现为视图。我正在使用我的 API,它非常有用。

    【讨论】:

      【解决方案2】:

      我会推荐 Active Model Serializers。

      我不推荐 RABL,你可能会得到一堆 n+1 的查询,个人 DSL 有点奇怪。

      为您的对象添加一个序列化程序。

      class LeituraSerializer < ActiveModel::Serializer
        attributes :id, pessoa_id, :livro_id
      end
      

      在你的控制器中你可以做

      class LeiturasController < ApplicationController
        def show
           @leituras = Leitura.find(params[:id])
      
          render json: @leituras
        end
      end
      

      在这里阅读更多:https://github.com/rails-api/active_model_serializers/blob/master/README.md

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-16
        • 1970-01-01
        • 2015-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多