ActiveRecord: validates_associated does not work when updating model?

孤者浪人 提交于 2019-12-25 02:29:06

问题


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:

  1. The validates_presence_of :price is not fired
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!