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.
314818dfe42ecd04a2b47abfaae5a63c?d=identicon&s=25 Adrian De la cruz (silverfang)
on 2007-07-13 12: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?
D5bbdf05c2eeaddf250774d2bca0657a?d=identicon&s=25 Khurram Ijaz (khurramijaz)
on 2007-07-13 12: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?
314818dfe42ecd04a2b47abfaae5a63c?d=identicon&s=25 Adrian De la cruz (silverfang)
on 2007-07-13 12: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!
E60b2dc57668b5662ce3f07781e41710?d=identicon&s=25 Matthew Rudy Jacobs (matthewrudy)
on 2007-07-13 14: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.