【发布时间】:2017-06-18 08:51:44
【问题描述】:
我有一个客户控制器来处理对属于公司的客户资源的请求。我希望能够通过 customer_id 或 phone_number 同时GET customers。 默认的 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
routes.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
【问题讨论】:
-
客户的样品反应如何?你能告诉我们吗?
-
{ "id": 1, "company_id": 1, "name": "john doe", "isActive": true, "created_at": "2j017-06-17T08:20:26.000 Z”,“updated_at”:“2017-06-17T08:20:26.000Z”,“移动”:0,“地址”:“”,“pan_number”:null,“tin_number”:null,“party_name”:“ " }
-
它将是包含客户详细信息的 JSON 响应
-
好的。那么你的控制器代码有什么问题?
标签: ruby-on-rails json rest ruby-on-rails-5