Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在RubyonRails中用一条sql语句创建大量行_Ruby On Rails_Postgresql - Fatal编程技术网

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})”