简体   繁体   English

将ActiveRecord查询转换为sql

[英]converting ActiveRecord query to sql

I need to write a migration to create some resources in a separate(new) table based on the existing records in another table 我需要编写迁移以根据另一个表中的现有记录在单独的(新)表中创建一些资源

This is basically what I need to do in RoR: 这基本上是我在RoR中需要做的事情:

  Note.all.each do |note|
    object_id = sprintf '%09d', note.id
    url_key = "notes/documents/#{object_id.scan(/.{3}/).join('/')}/original/#{note.document_file_name}"

    note.documents.create(s3_key: url_key)
  end

I need to loop through all the existing notes, and then create documents for them... ( as I'm migrating document from being a direct field on notes to a one_to_many association.) 我需要遍历所有现有注释,然后为它们创建文档...(因为我正在将document从注释中的直接字段迁移到one_to_many关联。)

How will this looks like in a sql query? sql查询中看起来如何? (specifically a postgresql query) (特别是一个PostgreSQL查询)

What you're looking for is an INSERT statement that inserts values from a query, which is part of the standard SQL spec. 您正在寻找的是INSERT语句,该语句从查询中插入值,这是标准SQL规范的一部分。 The trickier part with your question is breaking up the ID field into subfolders, which I've used a CTE to do (but not particularly cleverly) in this solution: 您的问题中比较棘手的部分是将ID字段分解为多个子文件夹,在此解决方案中,我使用CTE来做(但不是特别巧妙):

WITH noteparts AS (
  SELECT 
    id,
    document_file_name,
    substr(to_char(id, 'FM000000000'), 1, 3) as part_one,
    substr(to_char(id, 'FM000000000'), 4, 3) as part_two,
    substr(to_char(id, 'FM000000000'), 7, 3) as part_three
  FROM notes
)
INSERT INTO documents (note_id, s3_key)
SELECT id, 'notes/documents/' || part_one || '/' || part_two || '/' || part_three || '/' || document_file_name
FROM noteparts;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM