简体   繁体   English

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

[英]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 NoteActivity 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 :-您可以将此参数设为optionalrequires :-

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM