Forum: Ruby on Rails How can I implement uniqueness?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Adrian D. (Guest)
on 2007-07-13 14:02
Hello guys,


Suppose I have 2 models: Country and State.

The only field they have is called "name". And I want this field to be
unique in Country, and unique in State. But I want the uniqueness of the
State's name to be only within his Country.

So if I have a Country called "Mexico", I shouldn't be able to have to
States with the same name in there.
But I should be able to have one State called "Roca" in a Country called
"Japan", and another State called "Roca" in a different Country without
problems.

How can I achieve this?
Khurram I. (Guest)
on 2007-07-13 14:17
Put this in state
validates_uniqueness_of :name,:scope=>country_id

Khurram  Ijaz
http://www.renai-soft.com

Adrian De la cruz wrote:
> Hello guys,
>
>
> Suppose I have 2 models: Country and State.
>
> The only field they have is called "name". And I want this field to be
> unique in Country, and unique in State. But I want the uniqueness of the
> State's name to be only within his Country.
>
> So if I have a Country called "Mexico", I shouldn't be able to have to
> States with the same name in there.
> But I should be able to have one State called "Roca" in a Country called
> "Japan", and another State called "Roca" in a different Country without
> problems.
>
> How can I achieve this?
Adrian D. (Guest)
on 2007-07-13 14:20
Khurram Ijaz wrote:
> Put this in state
> validates_uniqueness_of :name,:scope=>country_id
>
> Khurram  Ijaz
> http://www.renai-soft.com
>


Thanks a lot!
Matthew Rudy J. (Guest)
on 2007-07-13 16:06
Adrian De la cruz wrote:
> Khurram Ijaz wrote:
>> Put this in state
>> validates_uniqueness_of :name,:scope=>country_id
>>
>> Khurram  Ijaz
>> http://www.renai-soft.com
>>
>
>
> Thanks a lot!

If you want to ensure this is the case
add a migration

add_index :states, [:country_id, :name], :unique => true

that's raise a MySQL error if you try and break the constraint.
This topic is locked and can not be replied to.