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

colorfulberry · 2014年09月03日 · 最后由 colorfulberry 回复于 2014年09月05日 · 1994 次阅读

例如 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? }

这样写行不行?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号