Rails rails validates 验证如何实现多个属性必须填一个

colorfulberry · September 03, 2014 · Last by colorfulberry replied at September 05, 2014 · 1996 hits

例如 user 表中有 fax,email,phone 三个属性 如何实现 fax,email,phone 有 email 值的时候 fax 和 phone 为空,有 fax 和 phone 的时候 email 为空的验证? @Rei

@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? }

这样写行不行?

You need to Sign in before reply, if you don't have an account, please Sign up first.