Reputation: 380
I am using rails4. I have a model, lets say human. Human has nested model Man. Man has attributes Name, Address, Number. I am trying to make an api in which i am not able to validate associated attributes. I was able to validate the man by using validates_associated, But my model is getting saved without validating the attributes name address and number. How can I validate their presence or mumericalitty if I am saving it from its parent controller? In humans controller I am saving Man like this
if @human.save
@man = @human.man.build
@man.name = params[:man][:name]
@man.address = params[:man][:address]
@man.number = params[:man][:number]
@man.save
How to validate these attributes before saving? Please help
Upvotes: 0
Views: 29
Reputation: 4811
usually, validations are placed in each respective model.
if human accepts_nested_attributes_for
man, placing a validation in man for the presence of those attributes should prevent you from saving both human and man during the building and saving process
Upvotes: 1
Reputation: 399
Use valid?
method. It will trigger validations defined in model and return true
or false
.
if @man.valid?
@man.save
else
#do smth else
Further reading: http://guides.rubyonrails.org/active_record_validations.html#valid-questionmark-and-invalid-questionmark
Upvotes: 0