class Member < ActiveRecord::Base
has_one :avatar
accepts_nested_attributes_for :avatar, allow_destroy: true
end
# 然后
member.avatar_attributes = { id: '2', _destroy: '1' }
member.avatar.marked_for_destruction? # => true
member.save
member.reload.avatar # => nil
上面举例是一对一,下面的一对多关系类似:
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 # => 2
member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
自动保存多个嵌套属性,有的可能不符合校验。
为了处理这种情况。你可以设置 :reject_if:
class Member < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts, reject_if: proc do |attributes|
attributes['title'].blank?
end
end
params = { 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 # => 2
member.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 :pages
reflection = Book._reflect_on_association(:pages)
Book.send(:add_autosave_association_callbacks, reflection)
Book.reflect_on_all_autosave_associations
update_only - 解决更新关联对象时的困扰
之前的写法:
# alias.rb
class Alias < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end