将ActiveRecord查询转换为PostgreSQL查询

时间:2018-06-28 21:08:53

标签: 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。

请告知。谢谢。

1 个答案:

答案 0 :(得分:0)

最终版本,对于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"
)