Failing validations in join model when using has_many :through

后端 未结 3 1296
被撕碎了的回忆
被撕碎了的回忆 2021-02-03 10:23

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

I have a join model ProductCategory with the following validations:



        
3条回答
  •  不要未来只要你来
    2021-02-03 11:12

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

    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]) #=> #
    

    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

    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)

    • 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

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

提交回复
热议问题