【发布时间】:2020-05-14 17:49:03
【问题描述】:
在我的 Ruby on Rails 应用中,自行车租赁公司可以管理他们所有的自行车(预订、付款等)。
上下文
我想为自行车租赁公司 (shops) 提供在他们自己的网站上实施预订表格的选项,这样他们就可以让客户预订bike。
- 然后此预订表格将显示
bike_categories,其中bikes可用于给定的arrival和departure日期。
问题
为了管理这个,我想生成一个 API 控制器操作,显示某个 bike_category 的 availability,显示属于这个 bike_category 的可用 bikes 数量的 count。
根据这篇文章
Design RESTful query API with a long list of query parameters
我应该能够在我的 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
路线
# 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
控制器/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
【问题讨论】:
-
@Int'lManOfCodingMystery 或不使用 POST 请求并发送查询参数...这显然是 POST 不适合的情况,因为您没有创建资源并且操作是幂等的。
标签: ruby-on-rails json api-design