如何单步将多个属性分配给 ActiveRecord::Relation 数组?

How to assign multiple attributes to ActiveRecord::Relation array in single step?

有一个函数 rails 可以在不保存(或更新)的情况下将属性分配给模型 ActiveRecord 实例(单个记录)。

例如:

$> 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'>

但 post 未保存在数据库中。

同样,我想对 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'>]>

您不能像这样在 rails 中进行批量分配

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

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

当您使用 Post.update_all 时,这是特殊的,因为它在数据库中运行 UPDATE ALL SQL 语句。因此不需要遍历内存中的集合。

更新 ruby 内存中的所有记录,另一方面,不能这样做;您确实需要遍历它们:

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

不过,这应该不是问题。我想不出在任何情况下您想要更新内存中的对象集合,而不想在某个时候迭代它们。