例如 user 表中有 fax,email,phone 三个属性 如何实现 fax,email,phone 有 email 值的时候 fax 和 phone 为空,有 fax 和 phone 的时候 email 为空的验证? @Rei
http://guides.rubyonrails.org/active_record_validations.html#custom-validators
@Rei OK thanks! 谢谢给的锚点链接 in user model
calss User < Application::Base attr_reader :user_properity validate :user_properity_should_be_presence private def user_properity_should_be_presence if email.blank? and (name.blank? or fax.blank?) errors.add(:user_properity, "必须输入有邮件或者fax和phone") end end valide
in _form.html
div calss="error"> <% if @user.errors[:user_properity].present? %> <%= @user.errors[:user_properity] %> <% end %> </div>
validates_presence_of :email, :if => lambda { |user| user.phone.nil? && user.fax.nil? }
这样写行不行?
@w7938940 woshishi
@w7938940 Thanks!