ruby - Ruby Activerecord 中的组合更新

标签 ruby activerecord

有没有更好的方法在 Ruby Activerecord(不是 Rails)中对我在这里所做的进行多次更新?我不想遍历所有记录并处理 if 或 case。

# reset all color fields to null
Signal.where.not(color: nil).update_all("color = null")
# set color field based on status
Signal.where(status: CONFIG.status.step3).update_all("color = 'o'")
Signal.where(status: CONFIG.status.step4).update_all("color = 'r'")
Signal.where(status: CONFIG.status.manual).update_all("color = 'y'")

最佳答案

也许你可以做得更多DRY并在 update_all 中对参数使用哈希样式而不是字符串:

# reset all color fields to null
Signal.where.not(color: nil).update_all(color: nil)
# set color field based on status
color_dependencies = {
  CONFIG.status.step3 => 'o', 
  CONFIG.status.step4 => 'r', 
  CONFIG.status.manual => 'y'
}

color_dependencies.each do |status, color| 
  Signal.where(status: status).update_all(color: color) 
end

关于ruby - Ruby Activerecord 中的组合更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35456458/

相关文章:

arrays - sort_by 哈希数组未在 ruby​​ 中给出预期结果

ruby-on-rails - 为什么 ORM 不自动在内存中设置反向关联?

activerecord - 兼容macruby的简单持久化框架?

ruby-on-rails - ActiveRecord find_all_by_X 是否保留顺序?如果不是,应该用什么代替?

ruby-on-rails - 回形针可以读取 S3 存储桶中的照片几何图形吗?

ruby - 如何在 Ruby 中快速生成字符串的所有排列?

ruby-on-rails - Michael Hartl 的 Rails 3 教程第 7 章中的 : Problem with has_password? 方法

ruby-on-rails - Ruby on Rails -- NameError '@' 不允许作为实例变量名

ruby-on-rails - 选择带有预加载的特定列

ruby-on-rails - rails : `includes` a `has_many` relation with `limit`