【问题标题】:Rails Active model serializer returns array instead of jsonRails Active 模型序列化程序返回数组而不是 json
【发布时间】:2016-07-29 23:56:56
【问题描述】:

我正在使用 Rails 创建包含基本待办事项信息的 API:名称、列表和项目。我希望它返回 json 格式,看起来像这样:

{
  "data": [
    {
      "type": "posts",
      "id": "1",
      "attributes": {
        "title": "JSON API is awesome!",
        "body": "You should be using JSON API",
        "created": "2015-05-22T14:56:29.000Z",
        "updated": "2015-05-22T14:56:28.000Z"
      }
    }
  ],
  "links": {
    "href": "http://example.com/api/posts",
    "meta": {
      "count": 10
    }
  }
}

^来自Active Serializer's Github的代码。

当我查看本地主机 http://localhost:3000/api/users/ 时,它会显示

[{"id":1,"username":"Iggy1","items":[{"id":1,"list_id":1,"name":"Wash dishes","completed":true},{"id":7,"list_id":1,"name":"Finish this assignment","completed":false}],"lists":[{"id":1,"name":"Important!","user_id":1,"permission":"private"},...

它返回一个哈希数组。我确信我在设置序列化程序时错过了一个重要步骤。如何将我的哈希数组重新格式化为 JSON API 格式?

我已经阅读了 getting started guiderenderingJSON API 部分,但我仍然无法弄清楚。我可能忽略了它。

我的一些代码:

app/serializers/user_serializer.rb

class UserSerializer < ActiveModel::Serializer
   attributes :id, :username#, :email
   has_many :items, through: :lists
   has_many :lists
end

app/controllers/api/users_controller.rb

   def index
     @users = User.all
     render json: @users, each_serializer: UserSerializer
   end

路线 Rails.application.routes.draw 做

  namespace :api, defaults: { format: :json } do

     resources :users do
       resources :lists
     end
  end
end

如果我能更好地澄清它,请告诉我。谢谢!!

【问题讨论】:

  • 您是否已声明要使用 JSON API 适配器?需要在您的配置中设置ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonApi。说明here
  • 成功了!谢谢 :)。我以前不知道该放在哪里。

标签: ruby-on-rails json active-model-serializers


【解决方案1】:

(来自cmets的回答)

要使用 JSON API 适配器,您需要声明要使用它。

 ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonApi

根据 AMS readme

【讨论】:

【解决方案2】:
ActiveModelSerializers.config.adapter = :json_api # Default: `:attributes`

来自0-10-stable documentation

但是,这并没有解决我的问题。这是由于在SO post

中讨论的那样嵌套了哈希

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 2013-12-18
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多