3

One of my models contains a virtual attribute called things. This attribute is an array, and I'd like every element within that array to be validated against a set of rules. Here is my current attempt at validation:

validates :things, presence: true,  length: { minimum: 2, maximum: 255 }

The problem with this code is that it validates the entire array itself, not each individual element within the array. I know I can write a custom validator, but is there any way to use the existing validation options to run these validations against every element in the array? The other topics I found on this are for older versions of Rails, so I'm not sure if Rails 4 has something new that could help with this.

Thanks in advance for any help!

1 Answer 1

1

Have you tried a custom validation? You can create a custom validation inside your model.

Something like this, where "things" is the name of the attribute that you want to validate:

model.rb

validate :check_each_thing

def check_each_thing
  things.each do |thing|
    if thing.present?
      if thing.size < 2 || thing.size > 255
        errors.add(:things, 'It should be longer than 2 and shorter than 255.')
      end
    else
      errors.add(:things, 'It should be present.')
    end
  end
end

Hope it helps :)

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Demi, thank you for the answer! As I mentioned in my question, I know I can write a custom validator, but I wanted to see if there is another way to accomplish this. It seems like this is my only option. Thank you for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.