繁体   English   中英

Rails-如何处理具有has_many关联错误的记录创建

[英]Rails - How to handle record create with has_many association error

尝试在具有has_many关联的模型上处理#create请求时遇到问题,其中已传递的ID之一不属于现有记录。

测试要求:

post authors_path, params: { book_ids: [-1] }

控制器方式:

def create
  @author= Author.create params
end

模型:

class Author
  has_many :books
end

这导致引发ActiveRecord::RecordNotFound错误。

问题如下:

我已经从ActiveRecord::RecordNotFound错误中解救出来,并在我的ApplicationController404 Record Not Found响应,因为当用户尝试对不存在的记录进行GETPATCHPUTDELETE时,通常会发生此类错误,例如, get author_path(-1) 我宁愿避免将rescue条款移至#show#create等方法上,因为我有很多控制器,从而导致重复代码很多。

我想保持记录和关联创建的原子性,这似乎是最好的方法,但是当发生上述情况时,我还想响应400 Bad Request 处理这种情况的最佳方法是什么?

更新

经过更多研究后,我编写了一个快速的自定义验证,用于验证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

这似乎不起作用,因为即使实例化一个新的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 ...

问题似乎是ActiveRecord尝试在进行任何验证之前为book_id传递的内容查找记录。 有什么办法可以挽救这个错误? 似乎对于此特定问题没有太多解决方法。

在StackOverflow之外向我建议的两个解决方案如下:

  1. 解决每个控制器动作中的错误

     class AuthorsController def create @author = Author.create(params) render json: @author rescue ActiveRecord::RecordNotFound => e render json_error_message end end 
  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM