Ruby on rails 如何在RubyonRails中用一条sql语句创建大量行
有了一个Ruby on rails 如何在RubyonRails中用一条sql语句创建大量行,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,有了一个拥有_many:games的用户模型和一个属于_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.
拥有_many:games
的用户模型和一个属于_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字段不能为空
如何解决此问题?您需要一个日期周围的报价,并在字段中添加
updated\u
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}")
您需要一个日期周围的报价,并在
字段中添加updated\u
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}")
尝试在日期中添加引号(“{Time.now},{user.id},{s})”
尝试在日期中添加引号(“{Time.now},{user.id},{s})”