设置了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

												

最新文章

  1. MongoDB初学
  2. Maven 小结
  3. 解析数据存储MySQL
  4. C#之使用随机数
  5. java基础知识回顾之java Thread类学习(三)--java线程实现常见的两种方式实现好处:
  6. Socket 入门
  7. CF 85D Sum of Medians (五颗线段树)
  8. poj2187 Beauty Contest(旋转卡壳)
  9. linux下virtualenv的python版本
  10. laravel5.3 笔记一
  11. C#中运算符的使用
  12. JS框架设计读书笔记之-动画
  13. linux的date的几个例子
  14. idea远程tomcat运行项目
  15. python的对象 变量
  16. 从零开始学spring cloud(十一) -------- hystrix监控
  17. Palindromic Numbers LightOJ - 1205
  18. SVN上传下载项目
  19. shader之法线变换
  20. 【Unity Shader】一、顶点函数(vertex)和片元函数(fragment)

热门文章

  1. spring 总结
  2. laravel发布订阅
  3. 什么是Rollback Segment(已truncate和delete 命令为例)?
  4. 基于Enterprise Architect完成数据库建模
  5. Web 开发技术文档大全
  6. python框架之Django(15)-contenttype模块
  7. mysql /tmp目录爆满问题的处理
  8. python调用RPC接口
  9. python类中的内置函数
  10. python 判断两个ip是不是处于同一网段