如何仅在不属于公司时才验证人员的地址?



在我的Rails 5应用程序中,我有以下设置:

class Client < ApplicationRecord
  has_one :address, :as => :addressable, :dependent => :destroy
  accepts_nested_attributes_for :address, :allow_destroy => true
end

class Company < Client
  has_many :people
end

class Person < Client
  belongs_to :company
end

class Address < ApplicationRecord
  belongs_to :addressable, :polymorphic => true
  validates :city,        :presence   => true
  validates :postal_code, :presence   => true
end

person can 属于company,但不一定要。

现在,我只想在该人不属于公司的情况下才能验证一个人的地址。如何完成?

也可能还有其他方法,但是根据我的经验,类似的事情应该起作用。

validates :address, :presence => true, if: -> {!company}

希望这会有所帮助。

验证可以采用ifunless参数,该参数接受方法,proc或字符串以确定是否运行验证。

在您的情况下:

validates :address, presence: true, unless: :company

根据注释更新以上仅照顾跳过验证本身,但是由于accepts_nested_attributes_for OP,试图坚持丢失的地址时仍会看到错误。这解决了:

accepts_nested_attributes_for :address, reject_if: :company_id

nabin的答案很好,但想以另一种方式显示。

validate :address_is_present_if_no_company
def address_is_present_if_no_company
  return if !company_id || address
  errors.add(:address, "is blank")
end

最新更新