Rails - Validate Presence Of Association?

后端 未结 4 631
耶瑟儿~
耶瑟儿~ 2020-11-29 18:58

I have a model A that has a \"has_many\" association to another model B. I have a business requirement that an insert into A requires at least 1 associated record to B. Is

4条回答
  •  失恋的感觉
    2020-11-29 19:25

    If you want to ensure that the association is both present and guaranteed to be valid, you also need to use

    class Transaction < ActiveRecord::Base
      belongs_to :bank
    
      validates_associated :bank
      validates :bank, presence: true
    end
    

提交回复
热议问题