2009-12-02 27 views
6

Tôi đang trả lời câu hỏi của riêng mình - chỉ cần đặt câu hỏi này lên đây cho google-fu trong trường hợp nó giúp người khác. Mã này cho phép bạn xác nhận sự hiện diện của một trường trong danh sách. Xem nhận xét trong mã để sử dụng. Chỉ cần dán vào lib/custom_validations.rb và thêm require 'custom_validations' để environment.rb của bạnLàm cách nào để bạn xác thực sự hiện diện của một trường từ nhiều số

#good post on how to do stuff like this http://www.marklunds.com/articles/one/312 

module ActiveRecord 
    module Validations 
    module ClassMethods 

     # Use to check for this, that or those was entered... example: 
     # :validates_presence_of_at_least_one_field :last_name, :company_name - would require either last_name or company_name to be filled in 
     # also works with arrays 
     # :validates_presence_of_at_least_one_field :email, [:name, :address, :city, :state] - would require email or a mailing type address 
     def validates_presence_of_at_least_one_field(*attr_names) 
     msg = attr_names.collect {|a| a.is_a?(Array) ? " (#{a.join(", ")}) " : a.to_s}.join(", ") + 
        "can't all be blank. At least one field (set) must be filled in." 
     configuration = { 
      :on => :save, 
      :message => msg } 
     configuration.update(attr_names.extract_options!) 

     send(validation_method(configuration[:on]), configuration) do |record| 
      found = false 
      attr_names.each do |a| 
      a = [a] unless a.is_a?(Array) 
      found = true 
      a.each do |attr| 
       value = record.respond_to?(attr.to_s) ? record.send(attr.to_s) : record[attr.to_s] 
       found = !value.blank? 
      end 
      break if found 
      end 
      record.errors.add_to_base(configuration[:message]) unless found 
     end 
     end 

    end 
    end 
end 

Trả lời

14

này làm việc cho tôi trong Rails 3, mặc dù tôi chỉ xác nhận cho dù cái này hay cái khác lĩnh vực đang hiện diện:

validates :last_name, :presence => {unless => Proc.new { |a| a.company_name.present? }, :message => "You must enter a last name, company name, or both"} 

Điều đó sẽ chỉ xác thực sự hiện diện của last_name nếu tên công ty trống. Bạn chỉ cần một vì cả hai sẽ trống trong điều kiện lỗi, do đó, để có một validator trên company_name cũng là dư thừa. Điều khó chịu duy nhất là nó phun ra tên cột trước tin nhắn, và tôi đã sử dụng câu trả lời từ câu hỏi this liên quan đến các thuộc tính nhân bản để tìm hiểu (chỉ cần thiết lập thuộc tính nhân bản last_name thành ""

+5

': trừ khi => ' company_name'' là true chỉ khi company_name là nil, không phải chuỗi rỗng. 'trừ => Proc.new {| a | a.company_name.present?}' cũng sẽ kiểm tra chuỗi rỗng. –

Các vấn đề liên quan