# Validation of other model fields

**URL:** <https://www.ruby-forum.com/t/validation-of-other-model-fields/103095>\
**Category:** Rails\
**Created:** [May 1, 2007, 8:18pm UTC](https://www.ruby-forum.com/t/validation-of-other-model-fields/103095 "2007-05-01T20:18:39Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Daniello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/22d042/32.png) [@Daniello](https://www.ruby-forum.com/u/Daniello)\
**Post date:** [May 1, 2007, 8:18pm UTC](https://www.ruby-forum.com/t/validation-of-other-model-fields/103095/1 "2007-05-01T20:18:39Z")

</div>

I’ve got in my Form not only fileds from my model but also fields from  
ither models. How can I validate them like other fields.

Example names od input tag fields

Name1 \<%= text\_field 'model1', 'name1' , :size =\> 40 %\>

Name2 \<%= text\_field 'model1', 'name2' , :size =\> 40 %\>

and from different model:

Name3 \<%= text\_field 'model2', 'name3' , :size =\> 40 %\>

How can I validate presence\_of field name3 from model2 model??

---

<div class="post-metadata">

**Author:** ![Daniello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/22d042/32.png) [@Daniello](https://www.ruby-forum.com/u/Daniello)\
**Post date:** [May 1, 2007, 9:33pm UTC](https://www.ruby-forum.com/t/validation-of-other-model-fields/103095/2 "2007-05-01T21:33:09Z")

</div>

Daniello wrote:

> I’ve got in my Form not only fileds from my model but also fields from  
> ither models. How can I validate them like other fields.
> 
> Example names od input tag fields
> 
> Name1 \<%= text\_field 'model1', 'name1' , :size =\> 40 %\>
> 
> Name2 \<%= text\_field 'model1', 'name2' , :size =\> 40 %\>
> 
> and from different model:
> 
> Name3 \<%= text\_field 'model2', 'name3' , :size =\> 40 %\>
> 
> How can I validate presence\_of field name3 from model2 model??

I’m not sure I understand your question.

Would your controller not say something like

model1.update\_attributes(params[“model1”])  
model2.update\_attributes(params[“model2”])

Then if you call

model1.save

it will not save if validation of model1 fails.

Likewise, model2.save will not save if model2 validation fails.

To save only if both validations pass you could call in your controller:

model1\_valid = model1.valid?  
model2\_valid = model2.valid?

if (model1\_valid && model2\_valid)  
model1.save\_with\_validation(false) # already validated  
model2.save\_with\_validation(false) # already validated  
else  
# How do you handle failed validations?  
end

But if your logic is that for this particular form, model2 should only  
be saved if user has entered a value for a certain field of model1, then  
you can perform that test in the controller:

if params[:model1][:certain\_field].blank?  
# handle error  
end

Stephan

---

<div class="post-metadata">

**Author:** ![Daniello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/22d042/32.png) [@Daniello](https://www.ruby-forum.com/u/Daniello)\
**Post date:** [May 1, 2007, 9:53pm UTC](https://www.ruby-forum.com/t/validation-of-other-model-fields/103095/3 "2007-05-01T21:53:48Z")

</div>

The update\_attributes method saves as well as updating the attribute.

b

---

<div class="post-metadata">

**Author:** ![Daniello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/22d042/32.png) [@Daniello](https://www.ruby-forum.com/u/Daniello)\
**Post date:** [May 2, 2007, 4:56pm UTC](https://www.ruby-forum.com/t/validation-of-other-model-fields/103095/4 "2007-05-02T16:56:32Z")

</div>

Daniello,

If there is a model association between the two models you can use the  
following (copy/pasted from [api.rubyonrails.org](http://api.rubyonrails.org)):

validates\_associated(\*attr\_names)

Validates whether the associated object or objects are all valid  
themselves. Works with any kind of association.

class Book \< ActiveRecord::Base  
has\_many :pages  
belongs\_to :library

```
validates_associated :pages, :library

```

end

Warning: If, after the above definition, you then wrote:

class Page \< ActiveRecord::Base  
belongs\_to :book

```
validates_associated :book

```

end

…this would specify a circular dependency and cause infinite  
recursion.

NOTE: This validation will not fail if the association hasn’t been  
assigned. If you want to ensure that the association is both present  
and guaranteed to be valid, you also need to use  
validates\_presence\_of.

Configuration options:

```
* on Specifies when this validation is active (default is :save,

```

other options :create, :update)  
\* if - Specifies a method, proc or string to call to determine if  
the validation should

occur (e.g. :if =\> :allow\_validation, or :if =\> Proc.new { |user|  
user.signup\_step \> 2 }). The method, proc or string should return or  
evaluate to a true or false value.

Regards,  
Bas van Westing

---

<div class="post-metadata">

**Author:** ![Daniello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/22d042/32.png) [@Daniello](https://www.ruby-forum.com/u/Daniello)\
**Post date:** [May 1, 2007, 10:03pm UTC](https://www.ruby-forum.com/t/validation-of-other-model-fields/103095/5 "2007-05-01T22:03:49Z")

</div>

On 1-May-07, at 3:51 PM, Ben M. wrote:

> > > Name3
> > 
> > Stephan  
> > Daniello, hopefully the following will help move you forward. It will  
> > leave you with an @errors for both models in your view that you can  
> > iterate over

When managing validations for multiple models in one action I  
typically use something like the following:

```
 @model1 = Model1.new(params[:model1])
 @model2 = Model2.new(params[:model2])

 respond_to do |format|
   if @ model1.valid? && @ model2.valid?
     #TODO: transaction here would help out
     @ model1.save(false)
     @ model1.save(false)
     flash[:notice] = 'Model1 and Model2 were successfully created.'
     format.html { render :partial => "my_partial" }
   else
     flash[:notice] = 'There were errors validating model1, model2'
     #merge_errors (below), merges the errors of 2 models into

```

one errors list  
format.html { @errors = merge\_errors(@model1, @model2);  
render :partial =\> “/error\_messages”, :errors =\> @errors, :status =\>  
500 }  
end  
end

#merges errors from 2 instances into 1 error object  
def merge\_errors(model1, model2)  
if model1.errors.size \> 0 && model2.errors.size \> 0  
model1.errors.instance\_eval { @errors.merge  
model2.errors.instance\_values[‘errors’] }  
elsif model1.errors.size \> 0  
model1.errors  
elsif model2.errors.size \> 0  
model2.errors  
else  
model1.errors  
end  
end

Cheers,  
Jodi  
General Partner  
The nNovation Group inc.  
www.nnovation.ca/blog

---

<div class="post-metadata">

**Author:** ![Daniello](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/22d042/32.png) [@Daniello](https://www.ruby-forum.com/u/Daniello)\
**Post date:** [May 2, 2007, 5:11pm UTC](https://www.ruby-forum.com/t/validation-of-other-model-fields/103095/6 "2007-05-02T17:11:37Z")

</div>

On 2-May-07, at 10:55 AM, Bas van Westing wrote:

> ```
> belongs_to :book
> 
> ```
> 
> validates\_presence\_of.  
> evaluate to a true or false value.
> 
> Regards,  
> Bas van Westing

now how did I miss that ?!

This is clearly a better route to go - for you and me, Daniello.

thanx Bas

Jodi
