我使用的是內置的API使用Rails 5.Rails的API:添加對象的數組JSON回報
我學習寫使用Rails的API,我試圖找出如何添加一個屬性,我的json返回的是一個對象數組。
我有一個用戶和帖子的模型。
我想要做的是返回與用戶關聯的所有帖子。
我所做的是在posts_controller.rb我已經得到了獲取用戶ID形成URL和返回的JSON,看起來像一個方法:
[{"id":1,"content":"My first post!","user":{"id":1,"firstname":"Jody","lastname":"White","email":"[email protected]","fullname_firstname_first":"Jody White"}},{"id":2,"content":"Rails School is awesome!","user":{"id":1,"firstname":"Jody","lastname":"White","email":"[email protected]","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
@jaydel更新了模型的帖子。 –