[英]Custom URL Param for Rails REST API
我有一個Customer控制器來處理對屬於Company的Customer資源的請求。 我希望能夠同時通過customer_id或phone_number 獲取客戶 。 默認的GET方法只能使我訪問customer_id和company_id 。 我應該如何修改我的路線以進行管理?
這是我的客戶控制器的代碼
class Api::V1::CustomersController < ApplicationController
respond_to :json
def show
customer_id = params[:id]
mobile_number = params[:mobile_number]
if mobile_number
customer = Customer.find(mobile_number)
render json: customer, status: 201
else
if customer_id
customer = Customer.find(customer_id)
render json: customer, status: 201
else
render json: { errors: "Customer ID and Phone Number is NULL" }, status: 422
end
end
end
end
route.rb文件:
Rails.application.routes.draw do
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# API routes path
get '/', :to => redirect('/index.html')
namespace :api, defaults: { format: :json } do
namespace :v1 do
resources :users, only: [:show, :create, :update, :index]
resources :sessions, only:[:create, :destroy]
resources :companies, only:[:create, :destroy] do
resources :products
resources :customers do
resources :invoices
end
resources :categories do
resources :products
end
end
resources :products, only:[:create, :destroy]
end
end
end
默認的GET方法只能讓我訪問customer_id和company_id。
實際上,它定義了參數的名稱,但是您可以隨時使用它。 在您的情況下,可以在id
和mobile_number
使用params[:id]
進行搜索,例如:
class Api::V1::CustomersController < ApplicationController
respond_to :json
def show
customer = Customer.find_by(mobile_number: params[:id])
if customer.empty?
customer = Customer.find(params[:id])
end
if customer.present?
render json: customer, status: 201
else
render json: { errors: "Customer ID and Phone Number is NULL" }, status: 422
end
end
end
因此,您可以在api調用中使用id
或mobile_number
; 例如,使用id
:
api/v1/companies/customer/1
或者,使用mobile_number
:
api/v1/companies/customer/55555555
這里唯一的問題是,如果id
是一個數字,而mobile_number
只有數字,那么您最終可能會有一個params[:id]
來查找同時具有id
和mobile_number
的Customer
; 它將返回由mobile_number
找到的Customer
。
如果這代表問題,那么您可以接收命名參數(通過查詢字符串)和與控制器上當前類似的設置1 ,只需解決在使用mobile_number
時查詢Customer
:
class Api::V1::CustomersController < ApplicationController
respond_to :json
def show
customer_id = params[:id]
mobile_number = params[:mobile_number]
if mobile_number
customer = Customer.find_by(mobile_number: mobile_number)
else
customer = Customer.find(customer_id)
end
if customer.present?
render json: customer, status: 201
else
render json: { errors: "Customer ID and Phone Number is NULL" }, status: 422
end
end
end
然后,你將只需要修改你的路由改變get
默認customers
:
resources :customers, except: [:show] do
resources :invoices
get '/customer', to: `customer#show'
end
並且api調用應指定要調用的參數; 例如,要求id
:
api/v1/companies/customer?id=1
要求mobile_number
:
api/v1/companies/customer?mobile_number=55555555
1 我稍微更改了邏輯以說明作為參數提供的有效id
或mobile_number
,但在customers
表上不存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.