params = { member: { name: 'joe', posts_attributes: [ { title: 'Kari, the awesome Ruby documentation browser!' }, { title: 'The egalitarian assumption of the modern citizen' }, { title: '', _destroy: '1' } # this will be ignored ]}}member =Member.create(params[:member])member.posts.length # => 2member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
自动保存多个嵌套属性,有的可能不符合校验。
为了处理这种情况。你可以设置 :reject_if:
classMember<ActiveRecord::Base has_many :posts accepts_nested_attributes_for :posts, reject_if: procdo|attributes| attributes['title'].blank?endendparams = { member: { name: 'joe', posts_attributes: [ { title: 'Kari, the awesome Ruby documentation browser!' }, { title: 'The egalitarian assumption of the modern citizen' }, { title: '' } # this will be ignored because of the :reject_if proc ]}}member =Member.create(params[:member])member.posts.length # => 2member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
在这里,效果和上面使用 _destroy: '1' 有类似之处。
重现 autosave 创建过程
Book has_many :pagesreflection =Book._reflect_on_association(:pages)Book.send(:add_autosave_association_callbacks, reflection)Book.reflect_on_all_autosave_associations