mysql - Rails MySQL 无法单个批量插入

标签 mysql ruby-on-rails activerecord

这是我在 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_idpromo_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/

相关文章:

mysql - 如何转置 MySQL 行并重复列标题?

ruby-on-rails - rails : (Devise) Two different methods for new users?

Mysql2::错误: 'sum_hours' 中的未知列 'field list'

ruby-on-rails - 如何安全地删除回形针附件上的链接?

sql - 简单的SQL问题(mysql)

java - 在 Hibernate 中保留 Joda 日期时间

ruby-on-rails - 多个具有并属于多个关系

php - 通过事件记录或查询获取拥有最多文章的用户及其数量

php - 序列化字符串中的偏移错误没有意义

ruby-on-rails - 不同文件类型的载波文件上传