ruby - 如何在一步中为 ActiveRecord::Relation 数组分配多个属性?
问题描述
有一个功能是 rails 可以在不保存(或更新)的情况下将属性分配给 ModelActiveRecord
实例(单个记录)。
例如:
$> post = Post.last #=> #<Post id: 53, title: 'Alpha', user_id: 39, state: 'published'>
$> post.assign_attributes(state: 'pending') #=> nil
$> post #=> #<Post id: 53, title: 'Alpha', user_id: 39, state: 'pending'>
但帖子未保存在数据库中。
同样,我想对ActiveRecord::Relation
.
例如:
$> posts = Post.where(state: 'published')
#=> #<ActiveRecord::Relation [#<Post id: 50, title: 'Wonderful', user_id: 39, state: 'published'>, #<Post id: 53, title: 'Alpha', user_id: 39, state: 'published'>]>
$> posts.assign_attributes(state: 'pending') #=> nil
$> posts
#=> #<ActiveRecord::Relation [#<Post id: 50, title: 'Wonderful', user_id: 39, state: 'pending'>, #<Post id: 53, title: 'Alpha', user_id: 39, state: 'pending'>]>
解决方案
您不能像这样在导轨中进行质量分配
posts.each {|post| post.assign_attributes(state: 'pending')}
each
执行操作,不改变性质posts
。所以posts
会是ActiveRecord::Relation
对象。
推荐阅读
- html - 如何获取 REST API 数据并在 html 页面中显示
- doctrine-orm - 原则防止数据库中不存在记录的 OneToOne 关联错误
- c# - 如何创建原始文件以获取字节数组?
- data-structures - 如何以定义明确的非自定义格式编写小数
- wordpress - Wordpress 多站点 Htaccess 覆盖
- python - 从一个开始枚举每组中的行
- apache-spark - 在 Spark SQL 中加入分区以获得更好的性能
- python-3.x - 将 Python 蓝牙套接字绑定到虚拟端口
- node.js - 当id包含“/”时如何通过id使用GET
- swift - 迅速。苹果系统。从扬声器录制声音