[英]Validates uniqueness in a one-to-many association
I have an Album model and Track model. 我有一个专辑模型和一个曲目模型。 I want to make sure that the name of each track on the album they belong to are unique. 我要确保专辑所属曲目中每个曲目的名称都是唯一的。 I tried using this validation in my Track
model 我尝试在Track
模型中使用此验证
validates :name, presence: true, uniqueness: true, scope: :album_id
but get the error: Unknown validator: 'ScopeValidator'
但收到错误: Unknown validator: 'ScopeValidator'
What am I doing wrong? 我究竟做错了什么?
class Album < ActiveRecord::Base
has_many :tracks
accepts_nested_attributes_for :tracks, :reject_if => :all_blank, :allow_destroy => true
validates :name, presence: true, uniqueness: true
end
class Track < ActiveRecord::Base
belongs_to :album
validates :name, presence: true, uniqueness: true, scope: :album_id
end
You need to scope the uniqueness, not put it as a separate argument. 您需要确定唯一性的范围,而不是将其作为单独的参数。
class Track < ActiveRecord::Base
belongs_to :album
validates :name, presence: true, uniqueness: { scope: :album_id }
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.