Baaju
Baaju

Reputation: 2012

Validate uniqueness of a field within a belongs_to, has_many relationship

I have two rails Active Record models groups and accounts

group

    has_many :accounts

    id 
    name
    .. other infromation
    timestamps


Account

    belongs_to :group

    id
    name
    .. other information
    timestamps

I need to do a validates :name, :uniqueness => true in the accounts section but only under a group. As in i want the account name to be unique under a group. I know i can enforce a database unique constraint but can i do this using AR ? Is it even possible ?

Upvotes: 1

Views: 3673

Answers (2)

Veraticus
Veraticus

Reputation: 16064

Try this:

validates :name, uniqueness: true, scope: :group_id

For more information on the options available to validate, check out the ActiveRecord Validations documentation.

Upvotes: 9

0lli.rocks
0lli.rocks

Reputation: 1072

I am not sure if the accepted answer ever worked but as of today (22.02.2022 and rails 5/6/7) it does not work. As many already suggested in the comments the correct way would be:

validates :name, presence: true, uniqueness: { scope: :group_id }

Upvotes: 0

Related Questions