Rails render json 返回数组而不是字典



如果我有一个标准的帖子资源(模型),并且在我的索引操作中有:

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
    render json: @posts
  end

而且@posts只有 1 个帖子,我得到的东西像

[{"id": 1, "title":"ImaPost"}]

但我(认为我)想找回更像的东西

{"posts": ["Post":{"id": 1, "title":"ImaPost"}]}

我尝试这样做的原因是因为我遵循本教程将 api 与 swift 一起使用 iOS 开发,但这是我第一次创建 API,也是我第一次使用 swift 这样的东西。

我相信

你想要:

def index
  @posts = Post.all
  render json: {posts: @posts}
end

最新更新