这是我在 Controller 中的创建方法:
def create
@promo = current_user.promos.build(promo_params)
if @promo.save
inserts = []
params[:user_limit].to_i.times do
inserts.push "(#{@promo.id}, #{SecureRandom.hex(3).upcase})"
end
sql = "INSERT INTO vouchers ('promo_id', 'promo_code') VALUES #{inserts.join(", ")}"
ActiveRecord::Base.connection.execute(sql)
redirect_to provider_promo_path(@promo), notice: 'Promo was successfully created.'
else
render :new
end
end
我的凭证表架构:
class Voucher < ActiveRecord::Base {
:id => :integer,
:promo_id => :integer,
:promo_code => :string,
:email => :string,
:status => :integer,
:user_id => :integer,
:created_at => :datetime,
:updated_at => :datetime
}
在上面的 Controller 方法中,我只想填写 promo_id
和 promo_code
字段。它会导致错误吗?这是错误消息返回:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''promo_id', 'promo_code') VALUES' at line 1: INSERT INTO vouchers ('promo_id', 'promo_code') VALUES
指向这一行:
ActiveRecord::Base.connection.execute(sql)
有什么建议吗?谢谢
更新
我已经编辑了我的代码:
inserts.push "(#{@promo.id}, '#{SecureRandom.hex(3).upcase}')"
但是我有另一个错误是:
ActiveRecord::StatementInvalid in Provider::PromosController#create
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''promo_id', 'promo_code') VALUES (20, 'C23E37'), (20, '2A70D0'), (20, '6557DC')' at line 1: INSERT INTO vouchers ('promo_id', 'promo_code') VALUES (20, 'C23E37'), (20, '2A70D0'), (20, '6557DC')
sql
变量值为:
"INSERT INTO vouchers ('promo_id', 'promo_code') VALUES (21, '0D8D52'), (21, '1F6E58'), (21, 'C049DC')"
为什么还是报错?
最佳答案
你可以换个方式试试。
为所有记录构建一个哈希数组:
inserts = []
params[:user_limit].to_i.times do
record = {}
record['promo_id'] = @promo.id
record['promo_code'] = "#{SecureRandom.hex(3).upcase}"
inserts << record
end
然后创建凭证:
Voucher.create(inserts)
关于mysql - Rails MySQL 无法单个批量插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709095/