Rails - Validate Nested Attributes Uniqueness with scope parent of parent

前端 未结 2 1790
遥遥无期
遥遥无期 2021-02-04 20:52

I have a problem with the scoped uniqueness validation in Rails for nested attributes with a parent of parent.

Background

I have a rails 4 appl

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 21:49

    I'll supply one possible solution. Not tested, but it should work, with a custom validation and an extra association.

    In your Account model:

    has_many :email_addresses, through: :contacts
    

    In your EmailAddress model:

    validate :uniqueness_of_mail
    
    private
    def uniqueness_of_mail
        account = contact.account
        if account.email_addresses.map(&:email).includes? email
            errors.add(email, 'Contact already has this email address')
            false
        else
            true
        end
    end
    

提交回复
热议问题