ActiveRecord Nested Atrributes 关联记录,对嵌套属性进行CURD

设置了Nested attributes后,你可以通过父记录来更新/新建/删除关联记录。

使用: #accepts_nested_attributes_for class method。


例如:

class Member < ActiveRecord::Base
has_one :author
has_many :posts accepts_nested_attributes_for :author, :posts
end

于是就增加了2个方法:XXX_attributes=(attributes)


分为2种情况:

  • one to one
  • ont to many

一对一的情况,生成的参数就是嵌套hash.

params = { member: { name: 'Jack', author_attributes: { icon: 'smiling' } } }

一对多的情况,参数包含了key :posts_attributes和它的属性,一个数组的hashes作为value。

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' 在 controller中的参数验证方法需要加上:
params.require(:member).permit(:name, posts_attributes: [:title, :_destroy]) _destroy:'1'是当加上参数all_destroy: true后,用于删除所有关联的选项。
一对多,也可以使用嵌套hash代替:
params = { member: {
name: 'joe',
posts_attributes: {
first: { title: 'Kari, the awesome Ruby documentation browser!' },
second: { title: 'The egalitarian assumption of the modern citizen' },
third: { title: '', _destroy: '1' } # this will be ignored
}
}}
 

options

具体用法见api

上一篇:Angular中通过$location获取地址栏的参数详解


下一篇:OpenStack中的Multipath faulty device的成因及解决(part 1)