简体   繁体   中英

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

validates :name, presence: true, uniqueness: true, scope: :album_id

but get the error: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM