开发者

and or operator in validates_presence_of of a Ruby on Rails model

开发者 https://www.devze.com 2022-12-22 20:26 出处:网络
I have an entry.rb model and I\'m trying to make a semi-complicated validation. I want it to require one or more of the following fields: phone, phone2, mobile, fax, email or website. How would you wr

I have an entry.rb model and I'm trying to make a semi-complicated validation. I want it to require one or more of the following fields: phone, phone2, mobile, fax, email or website. How would you write the intended code? Would something like this work?

validates_presence_of :phone and or :phone2 and or :mobile and or :fax and or :开发者_运维知识库email and or :website


You don't need the "and", "or" by itself will accomplish what you want.

It might be easiest to just write your own custom validation for this.

validate :contact_info

def contact_info
  unless phone or phone2 or mobile or fax or email or website
    errors.add_to_base "Must have at least one form of contact info"
  end
end

More details here: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

0

精彩评论

暂无评论...
验证码 换一张
取 消