简体   繁体   English

检查validates_presence_of以获取可变的属性集

[英]Check validates_presence_of for variable set of attributes

I have a object Product, with a category and some other attributes. 我有一个对象Product,带有类别和其他一些属性。 Different attributes are required in different categories. 不同类别中需要不同的属性。 Every attribute as an array of required_attributes. 每个属性都为required_attributes数组。 How should i implement this? 我应该如何实施呢? I tried something like this: 我尝试过这样的事情:

validates_presence_of lambda { *self.category.required_properties }

I also tryed this: 我也尝试过这个:

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

What would be the cleanest way of doing this? 这样做最干净的方法是什么? Thanks 谢谢

Try this: 尝试这个:

validates :name, :presence => true

or 要么

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

We can check using if record.category.present? 我们可以检查是否使用了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

You could set up a conditional validation for each attribute that checks if it is included in the list for the current category: 您可以为每个属性设置条件验证,以检查该属性是否包含在当前类别的列表中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM