gpt4 book ai didi

ruby-on-rails - 如何在 ruby​​ on rails 中使用单个 sql 语句创建大量行

转载 作者:行者123 更新时间:2023-11-29 14:09:43 27 4
gpt4 key购买 nike

有了一个 has_many :games 的用户模型和一个 belongs_to user 的游戏模型,我想使用 postgresql 数据库通过一个 sql 查询创建许多游戏。到目前为止我已经尝试过了

user=User.first
scores=[10,11,15,12] # a sample of a much larger array
values=scores.map{|s| "(#{Time.now},#{user.id},#{s})" }.join(",")
ActiveRecord::Base.connection.execute("INSERT INTO games (created_at,user_id, score) VALUES #{values}")

但我收到以下错误:

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "18"
LINE 1: ...(created_at, golfer_id, score) VALUES (2017-05-17 18:26:14 +...
^
: INSERT INTO games (created_at, golfer_id, score) VALUES (2017-05-17 18:26:14 +1000,10,10),(2017-05-17 18:26:14 +1000,10,11),(2017-05-17 18:26:14 +1000,10,15),(2017-05-17 18:26:14 +1000,10,12)
from /Users/Chris/.rvm/gems/ruby-2.2.2@golf_lab/gems/activerecord-5.0.2/lib/active_record/connection_adapters/postgresql/database_statements.rb:98:in `async_exec'

看起来时间格式不正确。我曾尝试在没有 created_at 字段的情况下创建游戏,但 postresql 抛出一个错误,表明 created_at 字段不能为 NULL。

如何解决这个问题?

最佳答案

您需要引用日期并添加 updated_at 字段。

values=scores.map{|s| "('#{Time.now}','#{Time.now}',#{user.id},#{s})" }.join(",")
ActiveRecord::Base.connection.execute("INSERT INTO games (created_at,updated_at, user_id, score) VALUES #{values}")

关于ruby-on-rails - 如何在 ruby​​ on rails 中使用单个 sql 语句创建大量行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44019720/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com