Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Unique names in the scope of a parent

Suppose I have:

class Author    
  has_many :books

class Book
  belongs_to :author
  validates :name, :presence => true, :uniqueness => true 

I want to change this so that the name of the book is only unique within the scope of the author, i.e. no author has two books with the same name, but two authors could have a book with the same name. Is this possible?

like image 910
user1231710 Avatar asked Feb 24 '12 21:02

user1231710


1 Answers

It's very possible and quite easy:

validates :name, :presence => true, :uniqueness => {scope: :author}
like image 192
Veraticus Avatar answered Oct 25 '22 14:10

Veraticus