在验证失败使用的has_many时加入模型:通过 [英] Failing validations in join model when using has_many :through

查看:84
本文介绍了在验证失败使用的has_many时加入模型:通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全code可以看出,在<一个href="https://github.com/andyw8/simpleform_examples">https://github.com/andyw8/simpleform_examples

My full code can be seen at https://github.com/andyw8/simpleform_examples

我有一个联接模式产品分类用下面的验证:

I have a join model ProductCategory with the following validations:

validates :product, presence: true
validates :category, presence: true

我的产品模式有以下关联:

has_many :product_categories
has_many :categories, through: :product_categories

当我尝试创建一个类,调用 @ product.save 控制器的新产品失败,!

When I try to create a new product with a category, the call to @product.save! in the controller fails with:

Validation failed: Product categories is invalid

当我删除了验证,一切正常和连接模型正确保存。

When I remove the validations, everything works and the join models are saved correctly.

我用 strong_parameters 但是我没有的认为的,应与此相关的问题。

I'm using strong_parameters but I don't think that should be related to this issue.

推荐答案

这是在回调链中的赛车状况。

This is a "racing condition" in the callback chain.

当你创建一个产品它没有它被保存在任何ID,因此也就不存在产品产品分类<范围/ code>。

When you create a product it doesn't have any id before it is saved, therefore there is no product in the scope of ProductCategory.

Product.new(name: "modern times", category_ids:[1, 2]) #=> #<Product id: nil >

在验证这一阶段(保存之前), ProductCatgory 不能以它的外键的product_id 指定任何标识。

At that stage of validation (before saving), ProductCatgory cannot assign any id to it's foreign key product_id.

这就是原因,你有关联验证:使验证发生在整个交易的范围

That's the reason you have association validations : so that the validation happens in the scope of the whole transaction

更新:正如评论说您仍然无法保证产品/类presence。有许多方法围绕这取决于你为什么要这么做(通过某种形式如直接进入产品分类)

UPDATE: As said in the comment you still can't ensure presence of a product/category. There's many ways around depending on why you want do this (e.g direct access to ProductCategory through some form)

  • 您可以创建一个标志,有验证:产品,presence:的确,如果:?direct_access
  • 如果你只能更新它们:验证:产品,presence:真的,在更新
  • 在第一个(在products_controller)创建你的产品后添加的类别
  • You can create a flag to have validates :product, presence: true, if: :direct_access?
  • or if you can only update them: validates :product, presence: true, on: "update"
  • create your product first (in the products_controller) and add the categories after

......不过说实在的,这些都是从简单的任何妥协或解决方法 @ product.create(PARAMS)

... But indeed these are all compromises or workarounds from the simple @product.create(params)

这篇关于在验证失败使用的has_many时加入模型:通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆