您可以在调用as_json 时包含与:include 选项的关联。
render json: @posts.as_json(include: :images)
您可以通过向Post 添加新关联来将其限制为一张图片。
class Post < ApplicationRecord
has_many :images
has_one :showcase_image, class_name: 'Image'
end
这将允许您改用:showcase_image。
render json: @posts.as_json(include: :showcase_image)
您也可以使用Jbuilder 来解决手头的问题,而无需添加额外的关联。
# app/views/posts/index.json.jbuilder
# Get images that belong to posts, group them by post_id and
# return the minimum image id for each post_id.
images = Images.where(post_id: @posts.select(:id)).group(:post_id).minimum(:id)
# Request the full image data for all image ids returned above.
images = images.keys.zip(Image.find(images.values)).to_h
json.array! @posts do |post|
json.extract! post, :id, :title, :body, :...
json.showcase_image do
image = images[post.id]
if image
json.extract! image, :id, :name, :location, :...
else
json.null!
end
end
end
在不调用特定渲染的情况下,Rails 将默认使用app/views/posts/index 文件,并选择与请求匹配的文件。 (如果您请求 HTML,它将查找 HTML 文件,如果您请求 JSON,它将查找 JSON,等等。)
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.all
end
end
现在,当您使用标头 Accept: application/json 请求 /posts.json 或 /posts 时,您的应用程序应该返回由 Jbuilder 构建的 JSON 响应。