# Validates\_uniqueness\_of: passing a method to :scope

**URL:** <https://www.ruby-forum.com/t/validates-uniqueness-of-passing-a-method-to-scope/149048>\
**Category:** Rails\
**Created:** [September 19, 2008, 8:24pm UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-passing-a-method-to-scope/149048 "2008-09-19T20:24:35Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mdaoust](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/dbc845/32.png) [@mdaoust](https://www.ruby-forum.com/u/mdaoust)\
**Post date:** [September 19, 2008, 8:24pm UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-passing-a-method-to-scope/149048/1 "2008-09-19T20:24:35Z")

</div>

I was wondering if anybody knows an easy way to pass a method name as  
the scope option to a validates\_uniqueness\_of validation on a AR model?

For example, I have nested models a bit like:

class Survey  
has\_many :areas  
end

class Area  
belongs\_to :survey  
has\_many :questions, :order =\> ‘position’  
validates\_uniqueness\_of :position, :scope =\> : survey\_id  
end

class Question  
belongs\_to :area  
validates\_uniqueness\_of :position, :scope =\> : area\_id  
end

So to get the questions on a survey, sorted by the ‘survey\_position’  
attribute I have to add a foreign key to the question, so that I can  
pass the survey\_id to the :scope argument on validates\_uniquess\_of. So,  
I have to add this stuff to Survey and Question classes:

class Survey  
has\_many :questions, :order =\> ‘questions.survey\_position’  
end

class Question  
belongs\_to :survey  
validates\_uniqueness\_of :survey\_position, :scope =\> :survey\_id  
end

This creates problems for when saves cascade down associated objects.

Any ideas on how to pass a method name as the scope option? Then I could  
add (instead of the above):

class Survey  
def questions  
find\_all\_questions.sort\_by(:survey\_position)  
end  
end

class Question  
validates\_uniqueness\_of :survey\_position, :scope =\>  
:survey\_id\_from\_area

def survey\_id\_from\_area  
area.survey.id  
end  
end

Any ideas?

~ Mark
