我的模型设置如下。一切正常,除了空白零件记录允许,即使所有零件和章字段均为空白。
class Book < ActiveRecord::Base
has_many :parts, inverse_of: :book
accepts_nested_attributes_for :parts, reject_if: :all_blank
end
class Part < ActiveRecord::Base
belongs_to :book, inverse_of: :parts
has_many :chapters, inverse_of: :part
accepts_nested_attributes_for :chapters, reject_if: :all_blank
end
class Chapter < ActiveRecord::Base
belongs_to :part, inverse_of: :chapters
end
Run Code Online (Sandbox Code Playgroud)
拼写代码,:all_blank替换为proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }。因此,我用它代替:all_blank并添加了一些调试功能。看起来正在发生的事情是该部件的pages属性响应的原因blank?,false因为它是一个实例化的哈希对象,即使它所包含的只是另一个仅包含空白值的哈希:
chapters_attributes: !ruby/hash:ActionController::Parameters
'0': !ruby/hash:ActionController::Parameters
title: ''
text: ''
Run Code Online (Sandbox Code Playgroud)
只是不是要这样工作吗?
我找到了一种解决方法:
accepts_nested_attributes_for :parts, reject_if: proc { |attributes| …Run Code Online (Sandbox Code Playgroud)