ActiveRecord Nested Atrributes 关联记录,对嵌套属性进行CURD
2024-10-12 20:42:21
设置了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
最新文章
- MongoDB初学
- Maven 小结
- 解析数据存储MySQL
- C#之使用随机数
- java基础知识回顾之java Thread类学习(三)--java线程实现常见的两种方式实现好处:
- Socket 入门
- CF 85D Sum of Medians (五颗线段树)
- poj2187 Beauty Contest(旋转卡壳)
- linux下virtualenv的python版本
- laravel5.3 笔记一
- C#中运算符的使用
- JS框架设计读书笔记之-动画
- linux的date的几个例子
- idea远程tomcat运行项目
- python的对象 变量
- 从零开始学spring cloud(十一) -------- hystrix监控
- Palindromic Numbers LightOJ - 1205
- SVN上传下载项目
- shader之法线变换
- 【Unity Shader】一、顶点函数(vertex)和片元函数(fragment)