Rails with Grape API - 参数中的关系 id 作为过滤器

Rails with Grape API - relation id in params as a filter

在我的 Rails/Grape API 应用程序中,我有一个端点,我在其中列出了所有用户注释。模型 Note 与模型 Activity 有可选关系(注释可以是 activity 的一部分,如下所示)。

class Note < ApplicationRecord
  belongs_to :user
  belongs_to :activity, optional: true
end

我的端点如下所示:

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

我想按活动过滤笔记(例如只显示 activities_id = 1 的笔记)。为此,我需要在参数中使用 activities_id 作为过滤器,但我不知道这种操作的语法是什么,如何实现?

在葡萄中获取参数的语法 API :-

desc 'Your description.'
params do
   requires :id, type: Integer, desc: 'Model ID.'
end
get do
   Model.find(params[:id])
end

所以根据你的代码:-

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

您可以将此参数设置为 optionalrequires :-

params do
   optional :activity_id, type: Integer, desc: 'Activity filter.'
end

params do
   requires :activity_id, type: Integer, desc: 'Activity filter.'
end