【发布时间】:2021-02-11 22:14:40
【问题描述】:
我正在根据客户端发送的 json 请求使用 ruby 实现搜索端点,该请求的格式应为 GET /workspace/:id/searches? filter[query]=旧&filter[type]=ct:Tag,User,WokringArea&items=5 控制器是这样的
class SearchesController < ApiV3Controller
load_and_authorize_resource :workspace, class: "Company"
load_and_authorize_resource :user, through: :workspace
load_and_authorize_resource :working_area, through: :workspace
def index
keyword = filtered_params[:query].delete("\000")
keyword = '%' + keyword + '%'
if filtered_params[:type].include?('User')
@users = @workspace.users.where("LOWER(username) LIKE LOWER(?)", keyword)
end
if filtered_params[:type].include?('WorkingArea')
@working_areas = @workspace.working_areas.where("LOWER(name) LIKE LOWER(?)", keyword)
end
@resources = @working_areas
respond_json(@resources)
end
private
def filtered_params
params.require(:filter).permit(:query, :type)
end
def ability_klasses
[WorkspaceAbility, UserWorkspaceAbility, WorkingAreaAbility]
end
end
respond_json以json格式返回资源,看起来是这样的
def respond_json(records, status = :ok)
if records.try(:errors).present?
render json: {
errors: records.errors.map do |pointer, error|
{
status: :unprocessable_entity,
source: { pointer: pointer },
title: error
}
end
}, status: :unprocessable_entity
return
elsif records.respond_to?(:to_ary)
@pagy, records = pagy(records)
end
options = {
include: params[:include],
permissions: permissions,
current_ability: current_ability,
meta: meta_infos
}
render json: ApplicationRecord.serialize_fast_apijson(records, options), status: status
结束
现在的问题是响应应该是这样的:
{
data: [
{
id: 32112,
type: 'WorkingArea'
attributes: {}
},
{
id: 33321,
type: 'User',
attributes: {}
},
{
id: 33221,
type: 'Tag'
attributes: {}
}
如何使我的代码支持响应具有不同类型的资源?
【问题讨论】:
标签: ruby-on-rails json ruby-on-rails-5 rails-api