Failing validations in join model when using has_many :through

后端 未结 3 1249
被撕碎了的回忆
被撕碎了的回忆 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 10:46

    Specifying inverse_of on your joining models has been documented to fix this issue:

    https://github.com/rails/rails/issues/6161#issuecomment-6330795 https://github.com/rails/rails/pull/7661#issuecomment-8614206

    Simplified Example:

    class Product < ActiveRecord::Base
      has_many :product_categories, :inverse_of => :product
      has_many :categories, through: :product_categories
    end
    
    class Category < ActiveRecord::Base
      has_many :product_categories, inverse_of: :category
      has_many :products, through: :product_categories
    end
    
    class ProductCategory < ActiveRecord::Base
      belongs_to :product
      belongs_to :category
    
      validates :product, presence: true
      validates :category, presence: true
    end
    
    Product.new(:categories => [Category.new]).valid? # complains that the ProductCategory is invalid without inverse_of specified
    

    Adapted from: https://github.com/rails/rails/issues/8269#issuecomment-12032536

提交回复
热议问题