简体   繁体   English

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

[英]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错误中解救出来,并在我的ApplicationController404 Record Not Found响应,因为当用户尝试对不存在的记录进行GETPATCHPUTDELETE时,通常会发生此类错误,例如, 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之外向我建议的两个解决方案如下:

  1. 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 
  2. 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.

相关问题 如何通过Rails 3.2中的关联在has_many中创建记录 - How to create records in has_many through association in rails 3.2 如何在Rails on Rails中创建像has_many关联这样的休眠状态? - How to create hibernate like has_many association in ruby on rails? 如何在has_many的中间模型中创建has_many关联:以最佳方式通过关联Rails - How to create has_many associations in the intermediate model of has_many :through association in an optimal way Rails Rails / Active Record has_many通过关联 - 获取记录 - Rails / Active Record has_many through association - fetching a record 如何创建has_many关系记录,如果关系记录已经存在于Rails 5中而不会出错? - How to create a has_many relationship record which won't error if the relationship record already exists in Rails 5? 如何使用has_many关联对Rails进行排序? - How to sort in rails with has_many association? 如何插入到 rails 中的 has_many 关联 - how to insert into has_many association in rails 使用 `:has_many:through` 记录关联处理复选框 forms - Handle check box forms with an `:has_many :through` Record Association Rails 6 - 通过记录创建 has_many - Rails 6 - create has_many through record Rails 4-通过has_many创建记录 - Rails 4 - Create record with has_many through
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM