检查validates_presence_of是否有变量属性集

时间:2012-12-24 19:50:08

标签: ruby-on-rails validation

我有一个对象产品,有一个类别和一些其他属性。 不同类别需要不同的属性。每个属性都是required_attributes的数组。 我应该如何实现这个? 我试过这样的事情:

validates_presence_of lambda { *self.category.required_properties }

我也试过这个:

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

这样做最干净的方法是什么? 感谢

2 个答案:

答案 0 :(得分:0)

试试这个:

validates :name, :presence => true

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

我们可以使用 if 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

答案 1 :(得分:0)

您可以为每个属性设置条件验证,以检查它是否包含在当前类别的列表中:

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