In Rails, how to respect :scope when using validates_uniqueness_of in an embedded object form?

Posted by mkirk on Stack Overflow See other posts from Stack Overflow or by mkirk
Published on 2010-05-28T19:12:44Z Indexed on 2010/05/28 19:22 UTC
Read the original article Hit count: 164

Filed under:
|

I have a Book model, which has_many Chapters (which belong_to a Book).

I want to ensure uniqueness of Chapter titles, but only within the scope of a single book. The catch is that the form for creating chapters is embedded in the Book model's form (The Book model accepts_nested_attributes_for :chapters).

Within the Chapter model:

 
validates_uniqueness_of(
    :chapter_title, 
    :scope => :book_id,
    :case_sensitive => false,
    :message => "No book can have multiple chapters with the same title.")

However, when I submit the Book creation form (which also includes multiple embedded Chapter forms), if the chapter title exists in another chapter for a different book, I fail the validation test.

Book.create( :chapters => [ Chapter.new(:title => "Introduction"), Chapter.new(:title => "How to build things")

=> Book 1 successfully created

Book.create( :chapters => [ Chapter.new(:title => "Introduction"), Chapter.new(:title => "Destroy things")
=> Book 2 fails to validate

second_book = Book.create( :chapters => [ Chapter.new(:title => "A temporary Introduction title"), Chapter.new(:title => "Destroy things")
=> Book 2 succesfully created

second_book.chapters[0].title= "Introduction"
=> success

second_book.chapters.save
=> success

second_book.save
=> success

Can anyone shed some light on how to do this? Or why it's happening?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord