我有一个Rails API。在REST API中删除外键的常用做法(路由和控制器操作)是什么?我的意思是不删除任何资源,只是将一对一关系上的外键设置为null
。
例如,我有一辆车,而该车只有一位顾客。
如果我要删除客户,它将是:
DELETE /vehicles/:id/customer
如果我只想在客户上设置vehicle_id: null
,我应该使用哪个端点和控制器?
答案 0 :(得分:1)
我不知道什么是常见做法,但是您可以设置routes.rb
类似于:
Rails.application.routes.draw do
...
resources :customers do
resources :vehicles, shallow: true
member do
put :remove_vehicle
end
end
...
end
哪个会给你类似的东西
customer_vehicles GET /customers/:customer_id/vehicles(.:format) vehicles#index
POST /customers/:customer_id/vehicles(.:format) vehicles#create
new_customer_vehicle GET /customers/:customer_id/vehicles/new(.:format) vehicles#new
edit_vehicle GET /vehicles/:id/edit(.:format) vehicles#edit
vehicle GET /vehicles/:id(.:format) vehicles#show
PATCH /vehicles/:id(.:format) vehicles#update
PUT /vehicles/:id(.:format) vehicles#update
DELETE /vehicles/:id(.:format) vehicles#destroy
remove_vehicle_customer PUT /customers/:id/remove_vehicle(.:format) customers#remove_vehicle
customers GET /customers(.:format) customers#index
POST /customers(.:format) customers#create
new_customer GET /customers/new(.:format) customers#new
edit_customer GET /customers/:id/edit(.:format) customers#edit
customer GET /customers/:id(.:format) customers#show
PATCH /customers/:id(.:format) customers#update
PUT /customers/:id(.:format) customers#update
DELETE /customers/:id(.:format) customers#destroy
在这种情况下,您将向remove_vehicle
添加一个CustomersController
操作。在该操作中,您将有权访问params[:id]
,可用于找到您的@customer
,然后执行类似的操作:
class CustomersController < ApplicationController
...
def remove_vehicle
@customer = Customer.find(params[:id])
@customer.update(vehicle_id: nil)
redirect_to :somewhere
end
...
end