创建嵌套属性时如何将唯一性范围限制为父级?

问题描述 投票:0回答:0

示例-

class Group < ApplicationRecord
 has_many :options
 accepts_nested_attributes_for :options
end

class Option < ApplicationRecord
 belongs_to :group
 validates :name, uniqueness: { scope: :group }
end

如果我尝试创建一个新组,我不想为同一组创建具有相同名称的重复选项。其他组可能有同名的选项。

Group.create({
age: 10,
option_attributes: [
{name: "Red"},
{name: "Red"},
],

Rails 有没有办法做到这一点?

我尝试添加验证,但失败了。

ruby-on-rails activerecord model rails-activerecord
© www.soinside.com 2019 - 2024. All rights reserved.