1

我有一个对象产品,具有类别和其他一些属性。不同的类别需要不同的属性。每个属性作为 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

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

4

2 回答 2

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
于 2012-12-24T19:58:45.440 回答
0

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

[:attribute1, :attribute2, :attribute3].each do |attribute|
  validates attribute, :presence => true,
    :if => Proc.new { |product| product.category.required_properties.include?(attribute) }
end
于 2012-12-25T06:44:32.943 回答