1

How can I apply validation on array elements so that it can raise an error that it can not be blank ??

    validates :my_arr , presence: true

It will check [" "].present? which will return true.But I need to check its element my_arr.last.

I have implemented following one in my model:

 if self.dma_area.last.blank?
   errors.add(:dma_area, "should be selected")
 end

I have tried it with lot of other option like (allow_blank: false exclusion etc) and I found above one is working but I am in doubt whether it is in rails standards.

Is above solution is fine according to rails standards/conventions.??

Waiting for good working solution.

2 Answers 2

2
validates :presence_of_last_element
...

private
... 
def presence_of_last_element
  unless my_arr.last.present?
    errors.add(:my_arr, "should not contain empty elements") 
end
Sign up to request clarification or add additional context in comments.

Comments

1

What you can do is use before_validation call back and reject all invalid values from your array. With that your normal validation should work fine.

You can try it like:

validates :my_arr , presence: true

before_validation :reject_invalid_values_from_my_arr
...

=====================
= Protected methods =
=====================
protected
  def reject_invalid_values_from_my_arr  
    self.my_arr = my_arr.compact.reject{|value| value.blank?}
  end
...

Comments

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.