1
votes

I'm newbie and and wondering if its possible to validate the presence of an array name not nil. Actually on my model I have

validates :name, presence: true

this prevents that from a web form is not possible to send the name blank, but as as soon name[] is an string_array and nil is an string, when I try to send [nil,nil] from curl it succeeds.

I found this: rails validation of presence not failing on nil and this ActiveRecord validation for nil and read the api http://edgeguides.rubyonrails.org/active_record_validations.html but I didn't found the clue.

Does anyone can help?

Thanks in advance.

Edit: with validates :name, presence: true, allow_nil: false doens't work. If I send and invalid name it succeeds. Example:

curl -X POST -d 'patient[name[]]=["Mathew","de Dios]"&patient[email][email protected]&patient[password]=123456&patient[password_confirmation]=123456&patient[sex]="female"&patient[doctor]=9' http://localhost:3000/api/patients.json

{**"success":true**,"data":{"active":null,"age":null,"created_at":"2013-08-15T11:19:03Z","dao":null,"day_active":null,"doctor_id":9,"email":"[email protected]","geo_ini":null,"id":2124,"migraine_triggers":null,**"name":[null]**,"password_digest":"$2a$10$say8LiNmnazWL/EWKBKtL.fa5pJLKe4mo8Sn.HD6w2jeUrc5vmTe2","phone":null,"remember_token":"iX4Ohuj_Z6c2mDQZ_5e2vw","rich":null,"sex":"\"female\"","updated_at":"2013-08-15T11:19:03Z"},"status":"created"}
2

2 Answers

1
votes

In the case that name is an array and that you want to check for nil elements, you can write a custom validation method. Here is an example :

validate :check_name_array_for_nil

def check_name_array_for_nil
    self.name.split(",").each do |x|
       if x.nil?
       errors.add(:name, "nil in name array")
       end
    end
end

EDIT: On second thought,this requires you to be storing the name as a string separated by commas.

0
votes

I'm not sure but with a strict validation maybe?

In the rails guide

class Person < ActiveRecord::Base
 validates :name, presence: { strict: true }
end

Person.new.valid?  # => ActiveModel::StrictValidationFailed: Name can't be blank

More info about the strict validation.