Failing validations in join model when using has_many :through

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

    Pretty sure you just need to define your relationships better. I still might have missed some, but hopefully you get the idea.

    class Product < ActiveRecord::Base
      include ActiveModel::ForbiddenAttributesProtection
    
      validates :name, presence: true
      validates :description, presence: true
      validates :color_scheme, presence: true
    
      belongs_to :color_scheme
    
      has_many :product_categories, inverse_of: :product
      has_many :categories, through: :product_categories
    end
    
    
    class ProductCategory < ActiveRecord::Base
      belongs_to :product
      belongs_to :category
    
      validates_associated :product
      validates_associated :category
    
      # TODO work out why this causes ProductsController#create to fail
      # validates :product, presence: true
      # validates :category, presence: true
    end
    
    
    class Category < ActiveRecord::Base
      has_many :product_categories, inverse_of: :category
      has_many :products, through: :product_categories
    end
    

提交回复
热议问题