提问人:vinnyWebDev 提问时间:11/17/2023 最后编辑:vinnyWebDev 更新时间:11/17/2023 访问量:36
在 Ruby on Rails 中销毁关联模型中的条目
Destroying an entry from an associated model in Ruby on Rails
问:
如果这是一个简单的问题,我很抱歉,我对轨道没有太多经验。我有一个用户 Cow 模型,它与 User 有属于的关系。我可以对用户执行 CRUD 操作没有问题。我可以对 Cow 模型进行创建和读取操作。我不知道该怎么做的是删除操作。我试图在解决方案中实现,但不断从 axios 中得到 500 个错误。
My routes seem to be ok
root GET / users#index
user_cows GET /users/:user_id/cows(.:format) cows#index
POST /users/:user_id/cows(.:format) cows#create
new_user_cow GET /users/:user_id/cows/new(.:format) cows#new
edit_user_cow GET /users/:user_id/cows/:id/edit(.:format) cows#edit
user_cow GET /users/:user_id/cows/:id(.:format) cows#show
PATCH /users/:user_id/cows/:id(.:format) cows#update
PUT /users/:user_id/cows/:id(.:format) cows#update
DELETE /users/:user_id/cows/:id(.:format) cows#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) ```
这是我尝试在控制器中实现的功能
class CowsController < ApplicationController
before_action :set_user, only: %i[ show edit update destroy ]
protect_from_forgery with: :exception, unless: -> {request.format.json?}
def create
@user = User.find(params[:user_id])
@cow = @user.cows.create(cow_params)
redirect_to user_path(@user)
end
#without this we get a 404. With it we get a 500, that's progress
def destroy
@user = User.find(params[:user_id])
@cow = @user.cows.find(params[:id])
@cow.destroy
end
private
def cow_params
params.require(:cow).permit(:tag, :dob, :sex, :breed, :dam, :docility, :agression, :fertility, :calving, :milk, :calf)
end
end
我的前端的请求如下。
async function deleteItem(e) {
e.preventDefault();
let response = await axios.delete(`http://localhost:3000/tickets/${props.id}`, { headers: { Accept: "application/json" } })
window.location.reload();
}
答: 暂无答案
评论