[英]Rails with Grape API - relation id in params as a filter
In my Rails/Grape API app I've got an endpoint where I listed all user Notes.在我的 Rails/Grape API 应用程序中,我有一个端点,其中列出了所有用户注释。 Model
Note
has optional relation with Activity
model (notes can be a part of activity, like below). Model
Note
与Activity
model 具有可选关系(注释可以是活动的一部分,如下所示)。
class Note < ApplicationRecord
belongs_to :user
belongs_to :activity, optional: true
end
My endpoint looks like this:我的端点如下所示:
module Notes
class Index < Base
desc 'All user notes',
success: { code: 200 },
failure: [
{ code: 401, message: 'The access token is invalid' },
{ code: 401, message: 'The access token expired' },
{ code: 404, message: "Couldn't find Notes" },
]
get do
::DetailedSerializer.new(
Note.where(user_id: current_user.id),
)
end
end
end
I want to filter notes by activities (eg show notes only for activities_id = 1
).我想按活动过滤笔记(例如,仅显示
activities_id = 1
的笔记)。 To do so I need to use activities_id
in params as filter but I don't know what is the syntax of such action, how to achieve that?为此,我需要在 params 中使用
activities_id
作为过滤器,但我不知道此类操作的语法是什么,如何实现?
Syntax for getting params in your grape API:-获取葡萄参数的语法 API:-
desc 'Your description.'
params do
requires :id, type: Integer, desc: 'Model ID.'
end
get do
Model.find(params[:id])
end
So according to your code:-所以根据你的代码: -
class Index < Base
desc 'All user notes',
success: { code: 200 },
failure: [
{ code: 401, message: 'The access token is invalid' },
{ code: 401, message: 'The access token expired' },
{ code: 404, message: "Couldn't find Notes" },
]
params do
optional :activity_id, type: Integer, desc: 'Activity filter.'
end
get do
## then you can use this id for filter in your query
puts "activity_id ====> #{params[:activity_id]} "
::DetailedSerializer.new(
Note.where(user_id: current_user.id),
)
end
end
You can make this param optional
or requires
:-您可以将此参数设为
optional
或requires
:-
params do
optional :activity_id, type: Integer, desc: 'Activity filter.'
end
OR或者
params do
requires :activity_id, type: Integer, desc: 'Activity filter.'
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.