# Validation across multiple models

**URL:** <https://www.ruby-forum.com/t/validation-across-multiple-models/136107>\
**Category:** Rails\
**Created:** [April 28, 2008, 11:32pm UTC](https://www.ruby-forum.com/t/validation-across-multiple-models/136107 "2008-04-28T23:32:17Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![niky81](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/51bf81/32.png) [@niky81](https://www.ruby-forum.com/u/niky81)\
**Post date:** [April 28, 2008, 11:32pm UTC](https://www.ruby-forum.com/t/validation-across-multiple-models/136107/1 "2008-04-28T23:32:17Z")

</div>

Hi, I’ve a Category model with fields:  
\*id  
\*name  
\*project\_id

and class defition:

* * *

class Category \< ActiveRecord::Base  
belongs\_to :project  
has\_many :choices  
has\_many :voices, :through =\> :choices  
validates\_presence\_of :project\_id, :message =\> “Selezionare un  
progetto.”  
end

* * *

the other model is Project with fields:

\*id  
\*name  
\*project\_type\_id

and class definition

* * *

class Project \< ActiveRecord::Base  
has\_many :voices, :order =\> :name  
has\_many :categories, :order =\> :name  
belongs\_to :project\_type  
validates\_presence\_of :name  
validates\_presence\_of :project\_type\_id

```
def project_type
  ProjectType.find(project_type_id).name if project_type_id
end

```

end

* * *

What I want is the ability to block category duplication but only when  
project\_type\_id of the project is 2.

I thought I could write something like this in the Category model:  
validates\_uniqueness\_of :name, :scope =\> :project\_id if  
Project.find\_by\_id(3).project\_type\_id == 2

which indeed works but how can I make dynamic using the project\_id of  
the current category? I mean I would like to replace  
…find\_by\_id(3)… with something like …find\_by\_id(project\_id)…

As an alternative I’ve tried also defining a validate method in the  
Category model but without luck, it always validates or invalidates the  
insertions.  
Thank you.

Nik

P.s. I’m just learning RoR and OOP so excuse my coding.
