views:

20

answers:

1

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?

A: 

it's because Book gets Chapters which have book_id set to NULL, and it does not set their book_id before validation b/c it have no id at this step.

first solution is to use Book.build_chapter() method, but it will require a separate method call for each chapter

second is to use accepts_nested_attributes_for and create a book like:

  book_attrs = {
    :chapters_attributes => [
      { :title => 'Intro' },
      { :title => 'Core' },
      { :title => 'Outro'}
    ]
  }

  book = Book.create(book_attrs)
zed_0xff
Isn't that what he's saying he did?
theIV
oh, I see.. I will edit my post.
zed_0xff