在Rails 3中进行必要的验证条件

时间:2012-07-25 20:41:37

标签: ruby-on-rails ruby-on-rails-3

如何根据另一个完全不同的字段的值对给定字段进行必要的验证?

2 个答案:

答案 0 :(得分:2)

尝试

attr_accessible :supplier_id, :supplier_type

validates :supplier_type, :presence  => true,
    :if => lambda{ check_supplier_exists }

def check_supplier_exists
  @supplier = Supplier.find(self.supplier_id)
  if @supplier != nil
    return true
  else 
    return false
  end
end

答案 1 :(得分:0)

检查除非conditions on validations

这里有example

class Person < ActiveRecord::Base

  validates :post_code, :presence => true, :unless => :no_postcodes?

  def no_postcodes?
    ['TW'].include?(country_iso)
  end

end