【发布时间】:2016-08-23 13:30:37
【问题描述】:
我正在使用 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!"
}
]
}
我如何才能或者我可以让数据以这样的方式返回?
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
【问题讨论】:
-
你能发布你的模型,展示所涉及的关联吗?我们可能不需要看到完整的模型。
-
@jaydel 用模型更新了帖子。
标签: ruby-on-rails ruby-on-rails-5 rails-api