2012-12-24 40 views
1

我有一个对象产品,具有类别和一些其他属性。 不同类别需要不同的属性。每个属性作为required_attributes的数组。 我应该如何实现这一点? 我想是这样的:检查validates_presence_of属性的变量集合

validates_presence_of lambda { *self.category.required_properties } 

我也tryed这一点:

def validate(record) 
    if record.category == nil 
     record.errors[:category] << "Has no Category" 
    else 
     recors.category.required_properties.each do |x| 
     .........????? 
     end 
    end 
end 

什么是这样做的最彻底的方法? 感谢

回答

0

你可以成立,如果它包含在列表为当前的类别,检查每个属性的条件验证:

[:attribute1, :attribute2, :attribute3].each do |attribute| 
    validates attribute, :presence => true, 
    :if => Proc.new { |product| product.category.required_properties.include?(attribute) } 
end 
0

试试这个:

validates :name, :presence => true 

validates :name, :presence => {:message => 'Name cannot be blank, Task not saved'} 

我们可以检查使用如果record.category.present?

def validate(record) 
    if record.category.present? 
     record.category.required_properties.each do |x| 
     .........????? 
     end 
    else 
     record.errors[:category] << "Has no Category" 
    end 
end 
+0

并为” ..... ??? ?”我可以做一些像“validate_presents_of x”x是符号吗? – kaibakker

+0

是的,你可以检查**如果x.present?**或**如果x.some_property.present?** ....就像明智的 –