首页 > 解决方案 > 如何在一步中为 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'>]>

标签: rubyruby-on-rails-4rails-activerecord

解决方案


您不能像这样在导轨中进行质量分配

posts.each {|post| post.assign_attributes(state: 'pending')}

each执行操作,不改变性质posts。所以posts会是ActiveRecord::Relation对象。


推荐阅读