How can I implement uniqueness?

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?

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?

Khurram Ijaz wrote:

Put this in state
validates_uniqueness_of :name,:scope=>country_id

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

Thanks a lot!

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.