In my Rails/Grape API app I've got an endpoint where I listed all user Notes. Model Note
has optional relation with Activity
model (notes can be a part of activity, like below).
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 (e.g. show notes only for 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?
Syntax for getting params in your grape 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
:-
params do
optional :activity_id, type: Integer, desc: 'Activity filter.'
end
OR
params do
requires :activity_id, type: Integer, desc: 'Activity filter.'
end