Rails MySQL无法单一质量插入

时间:2015-11-14 13:48:53

标签: mysql ruby-on-rails activerecord

这是我在控制器中的创建方法:

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
}

在上面的控制器方法中我只想填充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')"

为什么它仍然出错?

2 个答案:

答案 0 :(得分:0)

此:

inserts.push "(#{@promo.id}, #{SecureRandom.hex(3).upcase})"

应该是:

inserts.push "(#{@promo.id}, '#{SecureRandom.hex(3).upcase}')"

SecureRandom.hex(3).upcase是一个字符串,因此它应该在您的查询中引用。

另外,这是错误的:

INSERT INTO vouchers ('promo_id', 'promo_code')

应该是:

INSERT INTO vouchers (`promo_id`, `promo_code`)

您无法在MySQL中使用列名称周围的引号。

答案 1 :(得分:0)

你可以尝试另一种方式。

为您的所有记录构建一个哈希数组:

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)