[英]Rails - How to handle record create with has_many association error
I am running into a problem when trying to handle a #create
request on a model with a has_many
association where one of the passed in IDs does not belong to an existing record. 尝试在具有has_many
关联的模型上处理#create
请求时遇到问题,其中已传递的ID之一不属于现有记录。
Test request: 测试要求:
post authors_path, params: { book_ids: [-1] }
Controller method: 控制器方式:
def create
@author= Author.create params
end
Model: 模型:
class Author
has_many :books
end
This results in an ActiveRecord::RecordNotFound
error being raised. 这导致引发ActiveRecord::RecordNotFound
错误。
The problem is as follows: 问题如下:
I am already rescuing from an ActiveRecord::RecordNotFound
error and responding with 404 Record Not Found
in my ApplicationController
because such an error typically arises when a user is attempting to GET
, PATCH
, PUT
, or DELETE
a record that does not exist, eg, get author_path(-1)
. 我已经从ActiveRecord::RecordNotFound
错误中解救出来,并在我的ApplicationController
以404 Record Not Found
响应,因为当用户尝试对不存在的记录进行GET
, PATCH
, PUT
或DELETE
时,通常会发生此类错误,例如, get author_path(-1)
。 I would prefer to avoid moving the rescue
clause onto the #show
, #create
, etc methods because I have a lot of controllers, resulting in a lot of duplicate code. 我宁愿避免将rescue
条款移至#show
, #create
等方法上,因为我有很多控制器,从而导致重复代码很多。
I want to keep my record and association creations atomic and this seems to be the best way to do it, but I also want to respond with a 400 Bad Request
when the situation described above occurs. 我想保持记录和关联创建的原子性,这似乎是最好的方法,但是当发生上述情况时,我还想响应400 Bad Request
。 What would be the best way to handle such a situation? 处理这种情况的最佳方法是什么?
UPDATE 更新
After some more research, I wrote a quick custom validation that validates a record exists for all passed in book_ids
经过更多研究后,我编写了一个快速的自定义验证,用于验证book_ids
所有传递的记录是否存在
class Author < ApplicationRecord
validate :books_exist
def books_exist
return if book_ids.blank?
Book.find book_ids
rescue ActiveRecord::RecordNotFound => e
errors.add e.message
end
end
This doesn't seem to work though as even instantiating a new Author
instance without saving it to the database throws an ActiveRecord::RecordNotFound
error: 这似乎不起作用,因为即使实例化一个新的Author
实例而不将其保存到数据库中也会引发ActiveRecord::RecordNotFound
错误:
> Author.new(association_ids: [-1])
Book Load (2.3ms) SELECT `books`.* FROM `books` WHERE `books`.`id` = -1
ActiveRecord::RecordNotFound: Couldn't find Book with 'id'=[-1]
from ...
The issue seems to be that ActiveRecord
attempts to find a record for the passed in book_id
before any validation occurs. 问题似乎是ActiveRecord
尝试在进行任何验证之前为book_id
传递的内容查找记录。 Is there any way to rescue this error? 有什么办法可以挽救这个错误? It seems like there's not much of a workaround for this particular issue. 似乎对于此特定问题没有太多解决方法。
The two solutions that were suggest to me outside of StackOverflow are as follows: 在StackOverflow之外向我建议的两个解决方案如下:
Rescue the error in each controller action 解决每个控制器动作中的错误
class AuthorsController def create @author = Author.create(params) render json: @author rescue ActiveRecord::RecordNotFound => e render json_error_message end end
Create a generic action in the ApplicationController
在ApplicationController
创建通用动作
class ApplicationController def create(model) instance_variable_set("@#(model.class.name}", model.create(params) rescue ActiveRecord::RecordNotFound => e render json_error_message end end class AuthorsController def create super(Author) end end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.