简体   繁体   中英

Check validates_presence_of for variable set of attributes

I have a object Product, with a category and some other attributes. Different attributes are required in different categories. Every attribute as an array of 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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