Rails 4活动记录验证 - 有条件地验证4个属性的相互依赖性存在

Mat*_*ieu 4 activerecord ruby-on-rails ruby-on-rails-4 rails-activerecord

我有一个包含10个属性的表单.

其中我有4个属性,我需要应用我称之为"互为条件存在"的Active Record验证.这些属性是

  • 地址第一行
  • 邮政编码
  • 国家

这意味着如果用户填写其中一个,那么所有其他人必须在场

到目前为止,我只能说,如果用户填写第一个属性"地址行1",那么所有其他属性必须存在.

但它并未验证所有可能组合中的所有MUTUAL存在.例如,如果用户让"地址行1"为空但填充了zipcode并将其他三个留空,我希望活动的不再验证表单,因为他应该被要求填写其他三个属性.对每个属性都是如此.

这该怎么做?

这是我目前的代码

规格/型号/用户

validates :address_line_1,
              presence: true,
              length: { maximum: 100,
                        minimum: 3 }
  validates :zipcode,
              presence: true, if: :address_line_1?,
              length: { maximum: 20,
                        minimum: 4} 
  validates :state,
              presence: true, if: :address_line_1?,                  
  validates :country,
              presence: true, :address_line_1?,                  
              length: { maximum: 50}  
Run Code Online (Sandbox Code Playgroud)

dre*_*-hh 6

只需用:address_line?支票填写其中一个填写的字段来替换条件:

  validates :address_line_1,
              presence: true, if: :address_entered?,
              length: { maximum: 100,
                        minimum: 3 }
  validates :zipcode,
              presence: true, if: :address_entered?,
              length: { maximum: 20,
                        minimum: 4


 validates :state,
              presence: true, if: :address_entered?,
  validates :country,
              presence: true, if: :address_entered?,
              length: { maximum: 50}

  def address_entered?
    address_line_1.present? || zipcode.present? || state.present? || country.present?
  end
Run Code Online (Sandbox Code Playgroud)