我在 Rails 5 中使用内置 API。
我正在学习使用 Rails 编写 API,并且我正在尝试弄清楚如何将属性添加到我的 json 返回值中,该属性是一个对象数组。
我有一个用户和帖子的模型。
我想做的是返回与用户相关的所有帖子。
我所做的是在 posts_controller.rb 中我有一个方法可以从 URL 获取用户 ID 并返回如下所示的 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!"
}
]
}
我该怎么做,或者我可以让数据像这样返回吗?
用户.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
用户 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
最佳答案
假设你定义了这个结构:
class Post < ApplicationRecord
belongs_to :user
end
class User < ApplicationRecord
has_many :posts
end
您可以使用 Active Record 序列化方法实现您想要的结构
to_json
.使用将在 respond_to
阻止您的 Controller 。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
更新
而不是使用
repond_to
块,您也可以使用:render json: @users, include: :posts
您的 Controller 将如下所示:
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
关于ruby-on-rails - Rails API : Adding array of objects to json return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39102652/