ruby-on-rails - 将 ActiveRecord 查询转换为 PostgreSQL 查询

标签 ruby-on-rails postgresql ruby-on-rails-3 activerecord

我正在尝试将这段 Rails 代码更新为原始 PostgreSQL

ValidationEmergency.with_deleted.where(
  code: 'aml_validation_failed', 
  service_name: 'ComplyAdvantage', service_type: nil).each do |e|
    e.update_attributes(
      {
        service_type: 'Screening',
        service_id:   e.message.split(', ').last.split(' => ').last.to_i
      }, without_protection: true
    )
  end

到目前为止我所拥有的(根据@fanta 的评论进行编辑)

ActiveRecord::Base.connection.execute("
  UPDATE validation_emergencies 
  SET 
    service_type = 'Screening', 
    service_id = (
      CAST ( array_upper(string_to_array(message, ' => '), 1) AS INTEGER )
    ) 
  WHERE 
    code = 'aml_validation_failed' 
  AND 
    service_name = 'ComplyAdvantage' 
  AND 
    service_type IS NULL"
)

服务类型正在正确更新,但 service_id 没有,仍在研究如何使用 postgresql 正确拆分和 gsub。

请指教。谢谢。

最佳答案

最终版本,对于 service_id 它将拆分消息,获取最后一个元素并将其转换为整数。

ActiveRecord::Base.connection.execute(
  "UPDATE validation_emergencies
   SET
     service_type = 'Screening',
     service_id =
       CAST ((string_to_array(message, ' => '))[array_upper(string_to_array(message, ' => '), 1)] AS INTEGER)
   WHERE
     code = 'aml_validation_failed'
   AND
     service_name = 'ComplyAdvantage'
   AND
     service_type IS NULL"
)

关于ruby-on-rails - 将 ActiveRecord 查询转换为 PostgreSQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51091269/

相关文章:

ruby-on-rails - Fixnum 和 Numeric 有什么区别

ruby-on-rails - 获取特定工作日的最接近日期

ruby-on-rails - rails 3 测试用例 error.on( :field) Vs. 错误 [:field]

ruby-on-rails - 获取本地Rails开发环境中的真实IP地址

sql - 子查询中错误命名的字段导致加入

sql - rails : How to query for all the objects whose every association have an attribute that is not null

python - GeoDjango:PostgreSQL 未运行迁移,对象没有属性“geo_db_type”

ruby-on-rails - 如何使用 Ruby MongoDB 驱动程序将文档字段值作为 ISODate 插入?

ruby-on-rails - Rails - 从 Controller 运行 rake 任务或新线程?

mysql - 带限制的 Stacking Rails 查询