验证belongs_to,has_many关系中字段的唯一性

Baa*_*aju 0 activerecord ruby-on-rails ruby-on-rails-3

我有两个rails Active Record模型组和帐户

group

    has_many :accounts

    id 
    name
    .. other infromation
    timestamps


Account

    belongs_to :group

    id
    name
    .. other information
    timestamps
Run Code Online (Sandbox Code Playgroud)

我需要在帐户部分进行验证:name,:uniqueness => true,但仅限于一个组.在我希望帐户名称在组下是唯一的.我知道我可以强制执行数据库唯一约束,但我可以使用AR吗?它甚至可能吗?

Ver*_*cus 9

试试这个:

validate :name, :uniqueness => true, :scope => :group_id
Run Code Online (Sandbox Code Playgroud)

有关可用于验证的选项的更多信息,请查看ActiveRecord Validations文档.