如何将查询参数传递给 Rails API 控制器?

tec*_*ion 1 json api-design ruby-on-rails

在我的 Ruby on Rails 应用程序中,自行车租赁公司可以管理他们的所有自行车(预订、付款等)。

背景 我想为自行车租赁公司 ( shops) 提供在自己的网站上实施预订表格的选项,这样他们就可以让客户预订bike.

  • 然后,该预订表格将显示bike_categories在给定日期bikes可以预订的航班。arrivaldeparture

问题 为了管理这个问题,我想生成一个 API 控制器操作,显示 某个availability特定的可用数量。 bike_categorycountbikesbike_category

根据这篇文章

使用一长串查询参数设计 RESTful 查询 API

我应该能够处理 api 中的查询,但是如何在 Rails 控制器中获取查询?

代码

楷模

class Shop < ApplicationRecord
  has_many :bike_categories, dependent: :destroy
  has_many :bikes, through: :bike_categories
  has_many :reservations, dependent: :destroy
end

class Reservation < ApplicationRecord
  belongs_to :shop
  belongs_to :bike
end

class Bike < ApplicationRecord
  belongs_to :bike_category
  has_many :reservations, dependent: :destroy
end

class BikeCategory < ApplicationRecord
  belongs_to :shop
  has_many :bikes, dependent: :destroy
end
Run Code Online (Sandbox Code Playgroud)

路线

# api
  namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :shops, only: [ :show ]
      resources :reservations, only: [ :show, :create ]
      resources :bike_categories, only: [:index, :show, :availability]
    end
  end
Run Code Online (Sandbox Code Playgroud)

控制器/api/v1/bike_categories_controller.rb


class Api::V1::BikeCategoriesController < Api::V1::BaseController
  acts_as_token_authentication_handler_for User, only: [:show, :index, availability]

  def availability
    # How to get the bike_category, arrival and departure?
  end

end
Run Code Online (Sandbox Code Playgroud)

max*_*max 6

Rails 在哈希中提供查询字符串参数,params这实际上是以下内容的混搭:

  • 请求主体(对于具有主体的 POST、PATCH、PUT 等方法)
  • 查询字符串
  • 路径中的命名段(params[:id]例如)。

所以其实没什么可说的:

class Api::V1::BikeCategoriesController < Api::V1::BaseController
  acts_as_token_authentication_handler_for User, only: [:show, :index, availability]
  def availability
    # How to get the bike_category, arrival and departure?
    bike_category = params[:bike_categories] 
    arrival = params[:arrival]
    departure = params[:departure]
  end
end
Run Code Online (Sandbox Code Playgroud)

但是您的路由配置不正确。您实际上没有 的路线availiblityonlyand选项except仅限制生成的默认 CRUD 路由的输出resources。有效值为:

  • 展示
  • 指数
  • 新的
  • 创造
  • 编辑
  • 更新
  • 删除

任何其他值都没有任何影响。如果你想添加额外的 RESTful 路由,你可以这样做:

resources :bike_categories, only: [:index, :show] do
  # GET .../bike_categories/:bike_category_id/availability 
  get :availability 

  # GET .../bike_categories/:id/availability 
  get :availability, on: :member

  # GET .../bike_categories/availability 
  get :availability, on: :collection
end
Run Code Online (Sandbox Code Playgroud)