Rails API:将对象数组添加到JSON返回

4

我正在使用Rails 5的内置API。

我正在学习如何使用Rails编写API,并尝试找出如何向我的JSON返回值添加一个对象数组属性。

我有一个用户和帖子的模型。

我想做的是返回与用户相关联的所有帖子。

我在posts_controller.rb中编写了一个方法,获取URL中的userID并返回类似以下的JSON:

[{"id":1,"content":"My first post!","user":{"id":1,"firstname":"Jody","lastname":"White","email":"t@t.com","fullname_firstname_first":"Jody White"}},{"id":2,"content":"Rails School is awesome!","user":{"id":1,"firstname":"Jody","lastname":"White","email":"t@t.com","fullname_firstname_first":"Jody White"}}]

但是我想返回类似于这样的结果:

{
    firstname: "Jody",
    lastname: "White",
    email: "whatever",
    posts: [{
        "id":1,"content":"My first post!"
        },
        {
            "id":2,"content":"Rails School is awesome!"
        }
    ]
}

我该如何获取数据并返回类似的结果?

user.rb 模型

class User < ApplicationRecord
  attr_accessor :fullname_firstname_first

  has_many :posts

  def fullname_firstname_first
    fullname_firstname_first = firstname + " " + lastname
  end
end

post.rb模型

class Post < ApplicationRecord
  belongs_to :user
end

users_controller.rb

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :update, :destroy]

  # GET /users
  def index
    @users = User.all
    render json: @users, include: :posts
  end

  # GET /users/1
  def show
    @user = User.find(params[:id])
    render json: @user, include: :posts
  end
end

请问您能否发布您的模型并展示涉及的关联吗?我们可能不需要看到完整的模型。 - user483040
@jaydel已更新帖子并添加了模型。 - James White
1个回答

4
假设您定义了以下结构:
class Post < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :posts
end

你可以使用Active Record序列化方法to_json来实现你想要的结构。在你的控制器中,应该使用respond_to块。 format.json { render json: @users, include: :posts } 因此,你的UsersController应该像这样:
class UsersController < ApplicationController
  def index
    # all users with all their posts 
    @users = User.all
    respond_to do |format|
      format.json { render json: @users, include: :posts }
    end
  end

  def show
    # single user and their posts
    @user = User.find(params[:id])
    respond_to do |format|
      format.json { render json: @user, include: :posts }
    end
  end
end

更新

除了使用respond_to块外,您还可以选择使用以下代码:

render json: @users, include: :posts

这将使您的控制器看起来像:

class UsersController < ApplicationController
  def index
    # all users with all their posts 
    @users = User.all
    render json: @users, include: :posts
  end

  def show
    # single user and their posts
    @user = User.find(params[:id])
    render json: @user, include: :posts
  end
end

在我的展示(show)方法中,我将render json: @user更改为render json: @user.posts,并且我得到了与原始帖子相同的格式。如果有影响的话,我正在使用Active Model Serializer。 - James White
我正在使用Rails 5,看起来respond_to已经被弃用了? 我找到一篇帖子说如果我想使用respond_to,则需要在application_controller.rb中添加“include ActionController :: MimeResponds”,但是当我这样做时,我得到了“status”:406,“error”:“不可接受”,“exception”:“#<ActionController :: UnknownFormat:ActionController :: UnknownFormat>”。 - James White
@Christian-G 我现在已经让我的控制器和方法看起来像你的了,但是我没有在响应中包含帖子。如果有帮助的话,请查看我编辑过的原始帖子中的模型。 - James White
你的控制器现在是什么样子? - Christian-G
@Christian-G 我的原始帖子已经更新,其中包含了 users_controller.rb 文件的部分内容。 - James White
@Christian-G,我搞定了。使用ActiveModelSerializer,我可以这样做render json: @user.as_json(include: :posts)。这将返回我要找的格式!谢谢! - James White

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接