问题
I have 2 models:
class Book < ActiveRecord::Base
has_many :book_versions
accepts_nested_attributes_for :book_versions, allow_destroy: true
validates_associated :book_versions
class BookVersion < ActiveRecord::Base
has_many :collection_items
has_many :collections, through: :collection_items
belongs_to :book
validates_presence_of :price, :isbn #<-- validates presence
Everything works fine and dandy when I go to books/new and create a book with multiple book versions. The validations fire when I leave the price or isbn blank.
However, after I create a book with multiple book versions and I go back to the edit form and I delete one of the prices of an existing associated book_version and I submit the book form, it "updates successfully the book successfully". There are 2 problems here:
- The
validates_presence_of :priceis not fired - The book version doesn't actually update.
Here's a copy of part of the params:
"book_versions_attributes"=>{"0"=>{"name"=>"alt", "isbn"=>"", "price"=>"", "famis_number"=>"", "famis_price"=>"", "weight_in_pounds"=>""}, "1"=>{"name"=>"bb", "isbn"=>"123123123123222222", "price"=>"", "famis_number"=>"", "famis_price"=>"", "weight_in_pounds"=>"1.0", "inventory"=>"08", "id"=>"1030"}, ...
Everything supposedly "saves", but when I check the database, the bb book_version still has the old price.
Why is it failing silently and why aren't my validations firing?
来源:https://stackoverflow.com/questions/21632576/activerecord-validates-associated-does-not-work-when-updating-model