我正在使用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