Rails - Validate Presence Of Association?

后端 未结 4 638
耶瑟儿~
耶瑟儿~ 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:38

    You can validate associations with validates_existence_of (which is a plugin):

    Example snippet from this blog entry:

    class Tagging < ActiveRecord::Base
      belongs_to :tag
      belongs_to :taggable, :polymorphic => true
      validates_existence_of :tag, :taggable
    
      belongs_to :user
      validates_existence_of :user, :allow_nil => true
    end
    

    Alternatively, you can use validates_associated. As Faisal notes in the comments below the answer, validates_associated checks if the associated object is valid by running the associated class validations. It does not check for the presence. It's also important to note that a nil association is considered valid.

提交回复
热议问题